#include "mashwelder.h"
#include "ui_mashwelder.h"
#include "common.h"
#include <QDebug>
#include <QTime>
#include <QDate>
#include <QDateTime>
#include <sys/types.h>
#ifdef Q_OS_LINUX
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/sockios.h>
#include <linux/ethtool.h>
#endif
#include <QtNetwork>
#include <QHostInfo>
#include <QNetworkInterface>
#include "login/logindialog.h"
#include "DataBase/database.h"
#include "DataBase/databasequery.h"
#include "DataBase/dbtab_warn.h"
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonDocument>
#include "input/inputdialog.h"
#include "DataBase/dbtab_productionorder.h"
#include <QMessageBox>
#include "DataBase/dbtab_mashwelder.h"
#include "Setting/BasicSetting/basicsettingwidget.h"
#include "Setting/BasicSetting/electrodesetwidget.h"
#include "SettingReader/settingreader.h"
#include <QDomDocument>
#include "perssiondlg.h"

#define FINISH_FLAG "1"
#include "../scale/scaleamendcalibration.h"
#include "videoip.h"
//#define SHOW   0
#define UserRole  "userrole"


#define TIME_SEND  30
#define FINISH_FLAG "1"
int MashWelder::m_systemStatus;
bool MashWelder::_isBroken = false;
bool MashWelder::Equipment_ckeck = false;
bool l_Equipment_ckeck = false;
bool MashWelder::QC_Scan_ckeck = false;
bool l_QC_Scan_ckeck = false;

bool MashWelder::_orderBegin = false;
QString  MashWelder::_inputVal;
MashWelder::MashWelder(MainWindow *parent) :
    MainWidget(parent),
    ui(new Ui::MashWelder),
    m_modbusWnd(NULL),
    timeId(startTimer(200)),
    onlinetimeId(startTimer(5000*10)),//50 seconds
    mStandardParaSetting(NULL),
    mWeldInfoSetting(NULL),
    m_ContactUsSet(NULL),
    mStandardPara(new StandardPara{"","","","","","","","","","","","","","","","","","","","","","","","",""}),
    m_standardpara_temp({"","","","","","","","","","","","","","","","","","","","","","","","",""}),
    m_WarnReord(NULL),
    m_LogonRightsEdit(NULL),
    m_heartBeatTimer(new QTimer(0)),
    m_freshLEDTimer(new QTimer(0)),
    m_updateCurrentCountTimer(new QTimer(0)),
    m_warnList({"ERR01 可控硅直通","ERR02 可控硅不导通","ERR03 过热","ERR04 过电流","ERR05 欠电流","ERR06 互感器量程过大","ERR07 存储数据出错","ERR08 没有同步信号","ERR09 导通时间超过10ms"}),
    AlarmList({"冷却水超温","","焊接电压异常","可控硅直通","可控硅不导通","过热","过电流","欠电流","互感器量程过大","存储数据出错","没有同步信号","导通时间超过10ms","","网络异常","等待刷卡","订单完成"}),
    m_warnCodeList({"ERR01","ERR02","ERR03","ERR04","ERR05","ERR06","ERR07","ERR08","ERR09"}),
    m_warnContentList({"可控硅直通","可控硅不导通","过热","过电流","欠电流","互感器量程过大","存储数据出错","没有同步信号","导通时间超过10ms"}),
    m_warnValueinfo(0),
    m_ultraSonicThread(NULL),
    m_temperatureThread(NULL),
    m_ammeterDate(NULL),
    m_register_flag(false),
    m_pos_currentCount(false),
    m_StandardParaText(new StandardParaText{"焊接规范号","预压时间","加压时间","缓升时间","焊接1时间","冷却时间","焊接2时间","维持时间","停止时间","实际焊接1电压","实际焊接2电压","焊接1电压","焊接2电压","焊接次数","焊接预置数","落料重量","实际数量","超声波距离","温度","耗电量","电压","物件数量"}),
    m_receiveData(""),
    m_defectiveNumber(0),
    /*----zhanglong*/
    Alarm_Count(0),/*Over temperture count*/
    l_systemStatus(0),
    m_postDeviceDetail_flag(false),
    m_warningTimes(0),
    m_DefVol(0.0),
    m_weldingTimes_temp(-1),
    m_currentCount_temp(""),
    m_orderFinish_flag(false),
    m_current_taskId(""),
    m_current_orderWorkNum(0),
    m_current_order_finished_weight(0.0),
    m_current_order_finished_count(0),
    m_scale_weight_temp(0.0),
    m_scale_count_calibrated(0),
    m_save_weight_flag(false),
    m_scaleAmendInstance(ScaleAmendCalibration::getobj()),
    m_electrode_totalCout(0),
    m_electrode_remainCount(0),
    m_electrode_preCount(0),
    m_ScrollWarnSwitch({false,false,false,false,false,false,false,false,false}),
    m_task_timeId(startTimer(500)),
    _weldEnableTimer(new QTimer(this)),
    _isWorking(false),
    _iNum(0),
    readScaleComDelay_count(0),
    _objToserver(QJsonObject())
{
    ui->setupUi(this);
    mParent = parent;
    connect(_weldEnableTimer, &QTimer::timeout, this, &MashWelder::slot_CloseWeldEnable);
    initUi();
    initFont();
    initModbusSetting();
    initScaleSerialSetting();
    initAmmeterScaleModbusSlave();
    initLEDcycleTime();
    initHttpClient();
    initHttpServer();
    initButtonSlot();
    initUltraSonicThread();
    initTemperatureThread();
    //initAmmeterScaleModbusSlave();
    initEventFilter();
    setOrderButtonHidden();
    initSpotDelayTime();
    initQCScanCheck();
    initOrderRecordShow();

    setWeldEnable_unChecked();
    while(false == _writeNum_arr.isEmpty() )
        _writeNum_arr.removeFirst();
    _timerSendToserver = new QTimer(this);
    _timerSendToserver->setSingleShot(true);
    connect( _timerSendToserver, &QTimer::timeout, [=](){
        sendOperatorAndMaterial();
    });

}



MashWelder::~MashWelder()
{
    //析构时 焊接使能发送复位
    m_modbusWnd->writeCmd("01","05","03","","RTU","","00 00",false);
    deleteFun();
    delete ui;
    deleteSubThread();
}

void MashWelder::initUi()
{
    ui->stackedWidget->setCurrentWidget(ui->page_mashwelder);
    ui->le_weld_standard_num->setText("0");
#ifndef SHOW
    ui->btn_start->setDisabled(true);
#endif
    ui->btn_preLoadValveOpen->setDisabled(true);
    ui->btn_weldEnable->setDisabled(false); //TODO 20180730 change true to false -- that can use the button
    ui->btn_weldCount_clear->setDisabled(false);//TODO 20180801 change true to false -- that can clear the weld count by him/herself;
    ui->btn_standardNum_set->setDisabled(false);//TODO 20180804 change true to false
    ui->pushButton_4->setDisabled(true);
    ui->btn_login->setDisabled(true);
    ui->le_defectiveNumber->setEnabled(false);
    ui->btn_elecEnable->setDisabled(true);
    //set text alignment
    ui->le_productNameTab->setAlignment(Qt::AlignRight);
    ui->le_workNumTab->setAlignment(Qt::AlignRight);
    ui->le_workTimeTab->setAlignment(Qt::AlignRight);
    ui->le_productName->setAlignment(Qt::AlignLeft);
    ui->le_workNum->setAlignment(Qt::AlignLeft);
    ui->le_workTime->setAlignment(Qt::AlignLeft);
    ui->lbl_orderNum->setAlignment(Qt::AlignLeft);
    /*
     *开机必须设置焦点，不然扫码枪获取不到焦点，识别不了 2018-04-21;
     */
    this->setFocus();
    ui->btn_firstProduction->hide();
    ui->btn_QcFirstCheck->hide();
    ui->btn_firstProduction->setEnabled(false);
    ui->btn_QcFirstCheck->setEnabled(false);
    ui->btn_orderCompleted->hide();
    ui->btn_orderCompleted->setEnabled(false);
    ui->lab_warnTimes->setText("");
    ui->spotCheckScroll->hide();
    ui->btn_orderShow->hide();
    ui->btn_weldEnable->setText("焊接开");
    ui->pushButton->hide();
    initComboBox();
    //m_electrode_remainCount= m_electrode_preCount - m_electrode_totalCout - mStandardPara->weldCount.toInt();//TODO 20180805
    //ui->le_electrode_remain_count->setText(QString::number(m_electrode_preCount));
    m_electrode_preCount = ElectrodeSetWidget::getElectrode_preCount();
    if (m_electrode_preCount==0){
        ElectrodeSetWidget::setPreCount(1000000);
    }
    m_electrode_remainCount = ElectrodeSetWidget::getElectrode_remainCount();
    ui->le_electrode_remain_count->setText(QString::number(m_electrode_remainCount));


    QString tips = tr("此订单数量已完成，请输入不良品数！");
    _msgDlg = new MyMessageDialog(tips,tr("提示!"),this,tr("否"),tr("确定"));
    _msgDlg->hideCancelBtn();
    _msgDlg->hideConfirmBtn();
    _msgDlg->showOkBtn();
    _msgDlg->hide();
    connect( _msgDlg, SIGNAL(sig_btnOk_clicked()), _msgDlg, SLOT(on_btn_ok_clicked()) );
    connect( this, SIGNAL(sig_btnOk_clicked()), _msgDlg, SIGNAL(sig_btnOk_clicked())  );
    connect(_msgDlg, &MyMessageDialog::sig_btnOk, [=](){
        ui->le_defectiveNumber->setFocus();
        QMouseEvent event(QEvent::MouseButtonPress, QPoint(),
                          Qt::NoButton, Qt::NoButton, Qt::NoModifier);
        QApplication::sendEvent(ui->le_defectiveNumber, &event);
        _msgDlg->hide();
    } );


}


void MashWelder::initHttpClient()
{
    connect(m_httpClient,   SIGNAL(startHttpWork()),                this,   SLOT(deviceCircleSend()));
    connect(m_httpClient,   SIGNAL(startHttpWork()),                this,   SLOT(updateCurrentCount()));
    connect(m_httpClient,   SIGNAL(registerOK(bool)),               this,   SLOT(receiveHttpRegisterOK(bool)));
    connect(m_httpClient,   SIGNAL(ipStatusSignals(bool)),          this,   SLOT(httpRegister_slots(bool)));
    connect(m_httpClient,   SIGNAL(sendUserPerssion(QString)),      this,   SLOT(receiveHttpUserPermission(QString)));
    connect(m_httpClient,   SIGNAL(sendStation_OfHttp(QString)),    this,   SLOT(receiveStation_fromHttp(QString)));
    connect(m_httpClient,   SIGNAL(postSerialNum_Signals()),        this,   SLOT(postSerialNum_Slots()));
    connect(m_httpClient,   SIGNAL(updateDeviceState_Signals()),    this,   SLOT(updateDeviceState_Slots()));
    connect(m_httpClient,   SIGNAL(orderConfirmOK()),               this,   SLOT(showOrderCheckOK_Tips()));
    connect(m_httpClient,   SIGNAL(getUserStrirng(QString)),        this,   SLOT(currentUserShow(QString)));
}

void MashWelder::initButtonSlot()
{    
    connect(ui->btn_preLoadValveOpen,   SIGNAL(clicked(bool)),                  this,                       SLOT(preLoadValveOpen_slot()));
    connect(ui->btn_weldEnable,         SIGNAL(clicked(bool)),                  this,                       SLOT(weldEnable_Slot()));//
    connect(ui->btn_start,              SIGNAL(pressed()),                      this,                       SLOT(weldStart_PressCmd())); //start_press
    connect(ui->btn_start,              SIGNAL(released()),                     this,                       SLOT(weldStart_ReleaseCmd()));
    connect(ui->btn_weldCount_clear,    SIGNAL(pressed()),                      this,                       SLOT(weldCountClear_PressCmd()));//
    //connect(ui->btn_weldCount_clear,    SIGNAL(released()),                     this,                       SLOT(weldCountClear_ReleaseCmd()));
    connect(ui->btn_warn_clear,         SIGNAL(clicked(bool)),                  this,                       SLOT(weldWarnClearCmd()));
    connect(ui->btn_standardNum_set,    SIGNAL(clicked(bool)),                  this,                       SLOT(showStandardParaSetting()));
    connect(ui->btn_warnRecord_query,   SIGNAL(clicked(bool)),                  this,                       SLOT(showQueryWarnTable()));
    connect(ui->btn_contact,            SIGNAL(clicked(bool)),                  this,                       SLOT(showContactUsSetting()));
    connect(ui->btn_login,              SIGNAL(clicked(bool)),                  this,                       SLOT(showLogonRightsEditSetting()));
    connect(ui->le_weld_standard_num,   SIGNAL(editingFinished()),              this,                       SLOT(writeStandardPara()));
    connect(ui->le_weld_standard_num,   SIGNAL(selectionChanged()),             this,                       SLOT(termitTimer()));
    connect(ui->le_weld_standard_num,   SIGNAL(textEdited(QString)),            this,                       SLOT(termitTimer()));
    connect(ui->btn_close,              SIGNAL(longclicked()),                  this,                       SLOT(powerOff()));
    connect(ui->btn_firstProduction,    SIGNAL(clicked(bool)),                  this,                       SLOT(firstProductionOK_toScanOperator()));
    connect(ui->btn_firstProduction,    SIGNAL(clicked(bool)),                  this,                       SLOT(firstProductionOK_toScanOperator2()));

    connect(ui->btn_QcFirstCheck,       SIGNAL(clicked(bool)),                  this,                       SLOT(firstQcCheck2()));
    connect(ui->btn_QcFirstCheck,       SIGNAL(clicked(bool)),                  this,                       SLOT(firstQcCheck()));
    connect(ui->btn_orderCompleted,     SIGNAL(clicked(bool)),                  this,                       SLOT(orderCompleted_slots()));
    connect(ui->btn_resetWarn,          SIGNAL(longclicked()),                  this,                       SLOT(resetWarning()));
    connect(ui->comboBox_warning,       SIGNAL(currentIndexChanged(QString)),   this,                       SLOT(getCurrentTestVol(QString)));
    connect(ui->btn_spotCheck,          SIGNAL(clicked(bool)),                  this,                       SLOT(spotCheckManualExecute()));
    connect(ui->qc_scan_check,          SIGNAL(clicked(bool)),                  this,                       SLOT(QCCheckManualExecute()));

    connect(ui->btn_record,             SIGNAL(clicked(bool)),                  this,                       SLOT(recordScaleData_slots()));
    connect(ui->btn_orderShow,          SIGNAL(clicked(bool)),                  this,                       SLOT(showOrder()));
}

void MashWelder::deviceCircleSend()
{
    m_heartBeatTimer->start(3000);
    connect(m_heartBeatTimer,   SIGNAL(timeout()),    this,   SLOT(deviceCircleTimeSlot()));
}

void MashWelder::showOrder()
{
    showProductionOrder();
}

void MashWelder::initUltraSonicThread()
{
    m_ultraSonicThread = new UltraSonicThread();
    connect(m_ultraSonicThread,   SIGNAL(sendDistance(float)),    this,   SLOT(readUltraDistance(float)),Qt::QueuedConnection);
}

void MashWelder::clearWeldingCount()
{
    /*clear wled count ----zhanglong ---test---20181127*/
    m_modbusWnd->writeCmd("01","05","04","","RTU","","FF 00",false);// clear welding count cmd
    m_modbusWnd->writeCmd("01","05","04","","RTU","","00 00",false);// relase clear welding count cmd
}

void MashWelder::initLEDcycleTime()
{
    /*LED cnotrol time--zhanglong*/
    m_freshLEDTimer->start(800);
    connect(m_freshLEDTimer,   SIGNAL(timeout()),    this,   SLOT(LEDFrashCircleTimeSlot()));
}

void MashWelder::initTemperatureThread()
{
    m_temperatureThread = new TemperatureThread();
    connect(m_temperatureThread,   SIGNAL(sendTemp(float)),    this,   SLOT(readTemperature(float)),Qt::QueuedConnection);
}

void MashWelder::initAmmeterScaleModbusSlave()
{
    QString portName;
    portName = "/dev/" + m_usbPortName.port0_name;
    m_ammeterDate = new AmmeterScale(portName,"9600","8","none","1");

    //m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","01 00",false);

    connect(m_ammeterDate,   SIGNAL(sendAmmeterPowerData(float)),    this,   SLOT(readAmmeterPowerData(float)));
    connect(m_ammeterDate,   SIGNAL(sendAmmeterVolData(float)),    this,   SLOT(readAmmeterVolData(float)));

    /*init LED trun on green and rel----zhanglong*/
    m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","01 00",false);

}

void MashWelder::powerOff()
{
    m_httpClient->posShutDown(m_deviceInfo->deviceType, m_deviceInfo->deviceId, "shutdown", "offline");
    TSystem2("sudo reboot");
}

void MashWelder::qcCheckNG_AutoShowTips()
{
    ui->btn_weldEnable->setEnabled(false);
    QString tips = "请确认QC首检已通过，\n否则将在一小时内关闭焊接使你能～！";
    static MyMessageDialog *dialog = NULL;
    if(dialog == NULL)
    {
        dialog = new MyMessageDialog(tips,tr("确认"),this,tr("否"),tr("确定"));
        dialog->hideCancelBtn();
    }
    if(dialog->exec() == QDialog::Accepted)
    {
        dialog = NULL;
    }
}


void MashWelder::initEventFilter()
{
    ui->le_weld_standard_num->installEventFilter(this);
    ui->le_filterScale->installEventFilter(this);
    //ui->le_defectiveNumber->installEventFilter(this);
}

void MashWelder::deleteFun()
{
    if(m_scaleCom != NULL) {
        if(m_scaleCom->isOpen()){
            m_scaleCom->close();
        }
        delete m_scaleCom;
    }
    if(m_modbusWnd) {
        delete m_modbusWnd;
    }
    if(m_ammeterDate) {
        delete m_ammeterDate;
    }
    if(m_httpClient) {
        delete m_httpClient;
    }
    if(mStandardParaSetting) {
        delete mStandardParaSetting;
    }
    if(mWeldInfoSetting) {
        delete mWeldInfoSetting;
    }
    if(m_ContactUsSet) {
        delete m_ContactUsSet;
    }
    if(mStandardPara) {
        delete mStandardPara;
    }
    if(m_WarnReord) {
        delete m_WarnReord;
    }
    if(m_LogonRightsEdit) {
        delete m_LogonRightsEdit;
    }
    if(m_heartBeatTimer) {
        delete m_heartBeatTimer;
    }
    if(m_deviceInfo) {
        delete m_deviceInfo;
    }
}

void MashWelder::deleteSubThread()
{    
    if(m_ultraSonicThread)
    {
        m_ultraSonicThread->exit(0);
        delete m_ultraSonicThread;
    }
    if(m_temperatureThread)
    {
        m_temperatureThread->exit(0);
        delete m_temperatureThread;
    }
    ui->le_curr_weld2_vol->setText("0");
}

void MashWelder::timerEvent(QTimerEvent *event)
{
    int t = event->timerId();
    if(t == onlinetimeId)
    {
        m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"heartbeat","on-line-again");
    }
    if(t == timeId)
    {
        parseRawData();
        ui->lab_date->setText(QDate::currentDate().toString("yyyy-MM-dd"));
        ui->lab_time->setText(QTime::currentTime().toString("hh:mm:ss"));
    }
    if (t == m_task_timeId)
    {
        if ( !m_orderFinish_flag )
        {
            //订单完成2条件：
            //(1)合格品>=订单数 && 订单数>0 && 焊接次数>=订单数
            //(2)焊接次数 >= 订单数的103%
            if ((ui->le_calibratedCount->text().toInt() >= ui->le_workNum->text().toInt()  && ui->le_workNum->text().toInt() > 0
                      && ui->le_weldcount->text().toInt() >=ui->le_workNum->text().toInt())
                            || ( ui->le_weldcount->text().toInt() > 0
                                 && ui->le_weldcount->text().toInt() >= (int)( ui->le_workNum->text().toInt() * 3/100 + ui->le_workNum->text().toInt())
                                 && ui->le_workNum->text().toInt() > 0
                                )
               )

            {
                m_orderFinish_flag = true;
                m_systemStatus |= 0x8000;
                if (m_current_orderWorkNum!=0 && m_current_order_finished_count!=0)
                {
                    ui->le_defectiveNumber->setText(QString::number(qAbs(m_current_orderWorkNum - m_current_order_finished_count)) +" / " +
                                                    QString::number( (1-  qAbs(m_current_orderWorkNum - m_current_order_finished_count) / m_current_orderWorkNum) )
                                                    + "%");
                }

                if(ui->btn_weldEnable->isChecked())
                {
                    ui->btn_weldEnable->setChecked(false);
                    ui->btn_weldEnable->setText("焊接开");
                    m_modbusWnd->writeCmd("01","05","03","","RTU","","00 00",false);//焊接使能复位，不能焊接
                }

                {
                    endTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
                    _isWorking = false;
                    _iNum = 0;

                    //订单完成时，发5号数据、发7号数据
                    sendUpdateTodayTask();
                    send7Datas();

                    while(false ==_writeNum_arr.isEmpty() )
                    {
                        _writeNum_arr.removeFirst();
                    }

//                    QString tips = tr("此订单数量已完成，请输入不良品数！");
//                    MyMessageDialog *dialog = new MyMessageDialog(tips,tr("提示!"),this,tr("否"),tr("确定"));
//                    dialog->hideCancelBtn();
//                    dialog->show();

//                    connect(dialog, &QDialog::accepted, [=](){
//                        ui->le_defectiveNumber->setFocus();
//                        QMouseEvent event(QEvent::MouseButtonPress, QPoint(),
//                                          Qt::NoButton, Qt::NoButton, Qt::NoModifier);
//                        QApplication::sendEvent(ui->le_defectiveNumber, &event);
//                    } );

                    _msgDlg->show();
                    ui->btn_orderCompleted->setEnabled(true);
                    ui->le_defectiveNumber->installEventFilter(this);
                    _orderBegin = false;
                    QC_Scan_ckeck = false;
                    /*zhanglong -20181219*/
                    m_qc_checkDelayTimer->stop();
                }
            }
        }
        m_electrode_remainCount = ElectrodeSetWidget::getElectrode_remainCount();
        ui->le_electrode_remain_count->setText(QString::number(m_electrode_remainCount));
        m_electrode_preCount = ElectrodeSetWidget::getElectrode_preCount();
        if (m_electrode_preCount > 0)
        {
            ui->le_electrode_remainLife->setText(QString::number((float(m_electrode_remainCount) / float(m_electrode_preCount) )*100,'f',2));
        }
        else
        {
            ui->le_electrode_remainLife->setText(QString::number(0));
        }

        ui->le_filterScale->setText(QString::number( SettingReader::getFilterCoef()));
        ui->le_currentFinishedCount->setText(mStandardPara->scaleCount.trimmed());
    }
}

void MashWelder::setDefectValue()
{
    ui->le_defectiveNumber->setText("0");
}

void MashWelder::parseRawData()
{
    QByteArray buf;
    bool ok;
    char data;
    QStringList list;
    if(!m_receiveData.isEmpty())
    {
        list = m_receiveData.split(" ");
        for(int i = 0; i < list.count(); i++)
        {
            if(list.at(i) == " ")
                continue;
            if(list.at(i).isEmpty())
                continue;
            data = (char)list.at(i).toInt(&ok, 16);
            buf.append(data);
        }
        parseStandardPara(buf);
        buf.clear();
    }
}

bool MashWelder::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {

        if(watched == ui->le_weld_standard_num)
        {
            inputStandardNum(99,1);
        }
        else if (watched == ui->le_filterScale)
        {
            QWidget *back = new QWidget(this);
            back->setGeometry(0,0,SCREEN_WIDTH,SCREEN_HIGH);
            back->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);//Windows上设为透明色 需有Qt::FramelessWindowHint
            back->setAttribute(Qt::WA_TranslucentBackground,true);//Windows上设为透明色
            back->setWindowModality(Qt::WindowModal);
            back->show();
            inputDialog *inputdialog = new inputDialog(back,"模拟输入值",true,5,1000,0,true);
            inputdialog->setWindowModality(Qt::WindowModal);
            inputdialog->show();
            connect(inputdialog,SIGNAL(inputValue(float)),this,SLOT(acceptInputValue_test(float)));
            connect(inputdialog,SIGNAL(exitInputdialog()),back,SLOT(deleteLater()));
            connect(inputdialog,SIGNAL(exitInputdialog()),inputdialog,SLOT(deleteLater()));
        }
        else if(watched == ui->le_defectiveNumber)
        {
            inputDefectiveNum();//输入焊接不良品数
        }
        else if(watched == ui->le_calibratedCount)
        {
            inputGoodNum();
        }
    }
    return QWidget::eventFilter(watched,event);
}

void MashWelder::inputStandardNum(int max, int min)
{
    QWidget *back = new QWidget(this);
    back->setGeometry(0,0,SCREEN_WIDTH,SCREEN_HIGH);
    back->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); //Windows上设为透明色 需有Qt::FramelessWindowHint
    back->setAttribute(Qt::WA_TranslucentBackground,true); //Windows上设为透明色
    back->setWindowModality(Qt::WindowModal);
    back->show();
    inputDialog *inputdialog = new inputDialog(back,"模拟输入值",false,5,max,min,true);
    inputdialog->setWindowModality(Qt::WindowModal);
    inputdialog->show();
    inputdialog->setFullScreenShow();
    connect(inputdialog,SIGNAL(inputValue(int)),this,SLOT(acceptInputValue(int)));
    connect(inputdialog,SIGNAL(exitInputdialog()),back,SLOT(deleteLater()));
    connect(inputdialog,SIGNAL(exitInputdialog()),inputdialog,SLOT(deleteLater()));
    connect(this,SIGNAL(closeInputDialog_ByHeadMan()),inputdialog,SIGNAL(closeFullDialog_ByHeadMan()));
    connect(this,SIGNAL(closeSenconConfirmDialog_ByQcMan()),inputdialog,SIGNAL(closeSecondConfirmDialog_ByQcMan()));
}

void MashWelder::inputDefectiveNum()
{
    ui->le_defectiveNumber->clearFocus();
    QWidget *back = new QWidget(this);
    back->setGeometry(0,0,SCREEN_WIDTH,SCREEN_HIGH);
    back->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); //Windows上设为透明色 需有Qt::FramelessWindowHint
    back->setAttribute(Qt::WA_TranslucentBackground,true); //Windows上设为透明色
    back->setWindowModality(Qt::WindowModal);
    back->show();
    inputDialog *inputdialog = new inputDialog(back,"请输入不良品",false,5,0,0,true);
    inputdialog->setWindowModality(Qt::WindowModal);
    inputdialog->hideSome();
    inputdialog->show();
    connect(inputdialog,SIGNAL(inputValue(int)),this,SLOT(acceptDefectiveValue(int)));
    connect(inputdialog,SIGNAL(exitInputdialog()),back,SLOT(deleteLater()));
    connect(inputdialog,SIGNAL(exitInputdialog()),inputdialog,SLOT(deleteLater()));
}

void MashWelder::setCurrentStandardPara_ByOrder(ProductionVariant &tInfo)
{
    Q_UNUSED(tInfo);
    //receiveStandPapa_ofStandSet(tInfo.Mtype3.toInt());//TODO maybe not need to set standard data //TODO 20180718 remove  not need this
}

void MashWelder::sendCloseInputDialogSignal_ByHeadMan()
{
    emit closeInputDialog_ByHeadMan();
    StandardParaSetting::_bHeadManPass = true;
}

void MashWelder::sendCloseConfirmDialogSignal_ByQcMan()
{
    emit closeSenconConfirmDialog_ByQcMan();
    StandardParaSetting::_bQcPass = true;
}

void MashWelder::initSpotDelayTime()
{
    m_spotDelayTimer->start(60000*60);//60 minute
    connect(m_spotDelayTimer,SIGNAL(timeout()),this,SLOT(spotCheckTimerTips()));
}

void MashWelder::initQCScanCheck()
{
    m_qc_checkDelayTimer->start(60000*120); //120 minute
    connect(m_qc_checkDelayTimer,SIGNAL(timeout()),this,SLOT(QCCheckTimerTips()));
}

void MashWelder::initOrderRecordShow()
{
    ProductionVariant productinfo;
    queryCurrentOrder(productinfo,"");
    if (!productinfo.TaskId.isEmpty() && !productinfo.ProductName.isEmpty() && !productinfo.WorkNum.isEmpty() )
    {
        showProductionOrder();
    }
}

void MashWelder::saveElectrodeCountToDataBase()
{
    int preCount = ElectrodeSetWidget::getElectrode_preCount(); //TODO 20180805
    DataBaseQuery query(DataBase::getDataBase());
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QMap<QString,QVariant> map_Save;
    map_Save.insert(DBTab_MashWelder::_TAB_MASHWELDER_ELECTRODE_PRE_COUNT,QVariant(preCount));
    map_Save.insert(DBTab_MashWelder::_TAB_MASHWELDER_ELECTRODE_CURRENT_COUNT,QVariant(mStandardPara->weldCount.toInt()));
    QDateTime currDateTime = QDateTime::currentDateTime();
    map_Save.insert(DBTab_MashWelder::_ADD_TIME,QVariant(/*QDateTime::currentDateTime()*/currDateTime));
    query.insert(DBTab_MashWelder::TAB_MASHWELDER,map_Save);
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();

    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QString str;
    str = "SELECT "
          " SUM(" + DBTab_MashWelder::TAB_MASHWELDER + "." + DBTab_MashWelder::_TAB_MASHWELDER_ELECTRODE_CURRENT_COUNT + ")"
                                                                                                                         " FROM "  + DBTab_MashWelder::TAB_MASHWELDER +
            " WHERE " + DBTab_MashWelder::TAB_MASHWELDER + "." + DBTab_MashWelder::_TAB_MASHWELDER_ELECTRODE_SAVE_FLAG + " = " + "\'"+ QString::number(0) + "\'";
    query.execQString(str);
    if (query.next()) {
        m_electrode_totalCout = query.value(0).toInt();
    }

    QString str_query_id = "select _id  from tab_mashwelder order by _id desc limit 1";
    int currID = 0;
    query.execQString(str_query_id);
    if (query.next()) {
        currID = query.value(0).toInt();
    }
    QMap<QString,QVariant> map_insert;
    QString option = DBTab_MashWelder::_ID + " =' " + currID + "'" ;
    option += " AND " +DBTab_MashWelder::_TAB_MASHWELDER_ELECTRODE_SAVE_FLAG + " =' " + QString::number(0) + "'";

    map_insert.insert(DBTab_MashWelder::_TAB_MASHWELDER_ELECTRODE_TOTAL_COUNT,QVariant(m_electrode_totalCout));
    query.updateItem(DBTab_MashWelder::TAB_MASHWELDER,map_insert,option);
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();
}

void MashWelder::escFromSettings()
{
    m_electrode_remainCount = ElectrodeSetWidget::getElectrode_remainCount();
    ui->le_electrode_remain_count->setText(QString::number(m_electrode_remainCount));
}

void MashWelder::slot_hanjieguifanhao(ProductionVariant p )
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","00","01","RTU","02", p.ProcessId ,true);
}

void MashWelder::firstProductionOK_toScanOperator2()
{
    ui->btn_firstProduction->setDisabled(true);
}

void MashWelder::firstQcCheck2()
{
    ui->btn_QcFirstCheck->setDisabled(true);
}

void MashWelder::parseStandardPara(QByteArray array)
{
    if(array.isEmpty() && array.count()!=35)return;
    QStringList list;
    list.clear();
    QString  temp_str;
    temp_str.clear();
    for (int i=3;i<array.length(); i+=2)
    {
        int temp = (array.at(i)&0xFF)<<8 | (array.at(i+1)&0XFF);
        temp_str = QString::number(temp);
        list.append(temp_str);

    }

    for(int i =0;i<list.count();i++)
    {
        if(i==0){//焊接规范号
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_weld_standard_num->setText(temp);
            mStandardPara->weldStandardNum = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("1");
            }
        }
        if(i==1) {//SQ（预压时间）
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_sq->setText(temp);
            mStandardPara->sq = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("2");
            }
        }
        if(i==2) {//SO（加压时间）
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_so->setText(temp);
            mStandardPara->so = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("3");
            }
        }
        if(i==3) {//S1（缓升时间）
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_s1->setText(temp);
            mStandardPara->s1 = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("4");
            }
        }
        if(i==4) {//W1（焊接1时间）
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_w1->setText(temp);
            mStandardPara->w1 = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("5");
            }
        }
        if(i==5) {//CO（冷却时间）
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_co->setText(temp);
            mStandardPara->co = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("6");
            }
        }
        if(i==6) {//W2（焊接2时间）
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_w2->setText(temp);
            mStandardPara->w2 = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("7");
            }
        }
        if(i==7) {//HO（维持时间）
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_ho->setText(temp);
            mStandardPara->ho = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("8");
            }
        }
        if(i==8) {//OF（停止时间）
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_of->setText(temp);
            mStandardPara->of = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("9");
            }
        }
        if(i==9) {//W1焊接电压设置值
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_precurrvol->setText(temp);
            mStandardPara->preCurrVol = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("10");
            }
        }
        if(i==10) {//W2焊接电压设置值
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_weldcurrvol->setText(temp);
            mStandardPara->weldCurrVol = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("11");
            }
        }
        if(i==11) {//焊接电压1反馈值
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_curr_weld1_vol->setText(temp);
            mStandardPara->currWeld1Vol = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("12");
            }
        }
        if(i==12) {//焊接电压2反馈值
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_curr_weld2_vol->setText(temp);
            mStandardPara->currWeld2Vol = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("13");
            }
        }
        if(i==13) {//焊接计数器
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_weldcount->setText(temp);
            mStandardPara->weldCount = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("14");
            }
        }
        if(i==14) {//焊接预制数
            QString temp = list.at(i);
            temp = QString::number(temp.toFloat());
            ui->le_precount->setText(temp);
            mStandardPara->weldPreCount = temp;
            if(m_postDeviceDetail_flag) {
                putDetailFun("15");
            }
        }
    }
    /*
     *发送给子页面实时显示
     */
    emit standardPara_refresh(mStandardPara);
    judgingVolAlarms();
    list.clear();
}

void MashWelder::initFont()
{
    {
        QFont f("DejaVu Sans",16);
        ui->lab_date->setFont(f);
        ui->lab_time->setFont(f);
    }
    {
        QFont f("DejaVu Sans",19);
        ui->le_productNameTab->setFont(f);
        ui->le_productName->setFont(f);
        ui->le_workNumTab->setFont(f);
        ui->le_workNum->setFont(f);
        ui->le_workTimeTab->setFont(f);
        ui->le_workTimeTab_2->setFont(f);
        ui->le_workTime->setFont(f);
        ui->lbl_orderNum->setFont(f);
    }
    {
        QFont f("DejaVu Sans",26);
        ui->le_weldcount->setFont(f);


    }
    {
        QFont f("DejaVu Sans",18);
        ui->label_48->setFont(f);
        ui->label_52->setFont(f);
        ui->label_5->setFont(f);
        ui->label_6->setFont(f);
        ui->label_57->setFont(f);
        ui->label_32->setFont(f);
        ui->label_34->setFont(f);
        ui->label_3->setFont(f);
        ui->le_weld_standard_num->setFont(f);
        ui->le_status->setFont(f);
        ui->le_precount->setFont(f);
        ui->label_4->setFont(f);
        ui->label_7->setFont(f);
        ui->label_8->setFont(f);
        ui->label_9->setFont(f);
        ui->label_10->setFont(f);
        ui->label_11->setFont(f);
        ui->label_12->setFont(f);
        ui->label_13->setFont(f);
        ui->label_14->setFont(f);
        ui->label_15->setFont(f);
        ui->label_17->setFont(f);
        ui->label_29->setFont(f);
        ui->label_30->setFont(f);
        ui->label_58->setFont(f);
        ui->le_sq->setFont(f);
        ui->le_so->setFont(f);
        ui->le_s1->setFont(f);
        ui->le_w1->setFont(f);
        ui->le_co->setFont(f);
        ui->le_w2->setFont(f);
        ui->le_ho->setFont(f);
        ui->le_of->setFont(f);
        ui->le_sq->setFont(f);
        ui->le_sq->setFont(f);
        ui->le_sq->setFont(f);
        ui->le_defectiveNumber->setFont(f);
        //ui->le_currentFinishedCount->setFont(f);
        ui->lab_defectiveNumber->setFont(f);
        ui->le_curr_weld1_vol->setFont(f);
        ui->le_curr_weld2_vol->setFont(f);
        ui->le_precurrvol->setFont(f);
        ui->le_weldcurrvol->setFont(f);
        ui->le_sq->setReadOnly(true);
        ui->le_so->setReadOnly(true);
        ui->le_s1->setReadOnly(true);
        ui->le_w1->setReadOnly(true);
        ui->le_co->setReadOnly(true);
        ui->le_w2->setReadOnly(true);
        ui->le_ho->setReadOnly(true);
        ui->le_of->setReadOnly(true);
        ui->le_sq->setReadOnly(true);
        ui->le_sq->setReadOnly(true);
        ui->le_sq->setReadOnly(true);
        ui->le_curr_weld1_vol->setReadOnly(true);
        ui->le_curr_weld2_vol->setReadOnly(true);
        ui->le_precurrvol->setReadOnly(true);
        ui->le_weldcurrvol->setReadOnly(true);
        ui->comboBox_warning->setFont(f);
        ui->le_electrode_remain_count->setFont(f);
        ui->le_electrode_remainLife->setFont(f);

    }
    {
        QFont f("DejaVu Sans",16);
        ui->label_23->setFont(f);
        ui->label_24->setFont(f);
        ui->label_25->setFont(f);
        ui->label_18->setFont(f);
        ui->label_19->setFont(f);
        ui->label_26->setFont(f);
        ui->label_27->setFont(f);
        ui->label_28->setFont(f);
        ui->label_16->setFont(f);
        ui->label_22->setFont(f);
        ui->label_20->setFont(f);
        ui->label_21->setFont(f);
        ui->label_33->setFont(f);
        ui->label_35->setFont(f);
        ui->comboBox_warning->setFont(f);
    }
    {
        QFont f("DejaVu Sans",18);
        ui->btn_warn_clear->setFont(f);
    }
    {
        QFont f("DejaVu Sans",18);
        ui->btn_close->setFont(f);
        ui->btn_contact->setFont(f);
        ui->btn_login->setFont(f);
        ui->btn_preLoadValveOpen->setFont(f);
        ui->btn_standardNum_set->setFont(f);
        ui->btn_start->setFont(f);
        ui->btn_sysInfo->setFont(f);
        ui->btn_warnRecord_query->setFont(f);
        ui->btn_warn_clear->setFont(f);
        ui->btn_weldCount_clear->setFont(f);
        ui->btn_weldEnable->setFont(f);
        ui->btn_orderCompleted->setFont(f);
    }
    ui->le_precount->setReadOnly(true);
    ui->le_weldcount->setReadOnly(true);
    ui->le_status->setReadOnly(true);
    ui->le_precount->setText(QString::number(100));
#ifndef SHOW
    ui->btn_start->hide();
#endif
}

void MashWelder::posDetailFun(QString sequence)
{
    if(sequence.isEmpty())
    {
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接规范号",mStandardPara->weldStandardNum);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"预压时间",mStandardPara->sq);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"加压时间",mStandardPara->so);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"缓升时间",mStandardPara->s1);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接1时间",mStandardPara->w1);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"冷却时间",mStandardPara->co);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接2时间",mStandardPara->w2);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"维持时间",mStandardPara->ho);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"停止时间",mStandardPara->of);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"实际焊接1电压",mStandardPara->currWeld1Vol);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"实际焊接2电压",mStandardPara->currWeld2Vol);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接1电压",mStandardPara->preCurrVol);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接2电压",mStandardPara->weldCurrVol);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接次数",mStandardPara->weldCount);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接预置数",mStandardPara->weldPreCount);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"落料重量",mStandardPara->scaleWeight);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"超声波距离",mStandardPara->ultraSonicDistance);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"温度",mStandardPara->temperarture);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量",mStandardPara->ammeterData);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"实际数量",mStandardPara->scaleCount);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"不良品数",mStandardPara->defectiveNumber);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"累计数量",mStandardPara->totalCount_FromScale);//TODO 20180730 add need test
    }
}

void MashWelder::putDetailFun(QString sequence)
{
    if(!sequence.isEmpty()) {
        if(sequence.compare("1") == 0) {
            if(m_standardpara_temp.weldStandardNum != mStandardPara->weldStandardNum){
                m_standardpara_temp.weldStandardNum = mStandardPara->weldStandardNum;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接规范号",mStandardPara->weldStandardNum);
            }
        }
        else if(sequence.compare("2") == 0) {
            if(m_standardpara_temp.sq != mStandardPara->sq) {
                m_standardpara_temp.sq = mStandardPara->sq;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"预压时间",mStandardPara->sq);
            }
        }
        else if(sequence.compare("3") == 0) {
            if(m_standardpara_temp.so != mStandardPara->so) {
                m_standardpara_temp.so = mStandardPara->so;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"加压时间",mStandardPara->so);
            }
        }
        else if(sequence.compare("4") == 0) {
            if(m_standardpara_temp.s1 != mStandardPara->s1) {
                m_standardpara_temp.s1 = mStandardPara->s1;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"缓升时间",mStandardPara->s1);
            }
        }
        else if(sequence.compare("5") == 0) {
            if(m_standardpara_temp.w1 != mStandardPara->w1) {
                m_standardpara_temp.w1 = mStandardPara->w1;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接1时间",mStandardPara->w1);
            }
        }
        else if(sequence.compare("6") == 0) {
            if(m_standardpara_temp.co != mStandardPara->co) {
                m_standardpara_temp.co = mStandardPara->co;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"冷却时间",mStandardPara->co);
            }
        }
        else if(sequence.compare("7") == 0) {
            if(m_standardpara_temp.w2 != mStandardPara->w2) {
                m_standardpara_temp.w2 = mStandardPara->w2;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接2时间",mStandardPara->w2);
            }
        }
        else if(sequence.compare("8") == 0) {
            if(m_standardpara_temp.ho != mStandardPara->ho){
                m_standardpara_temp.ho = mStandardPara->ho;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"维持时间",mStandardPara->ho);
            }
        }
        else if(sequence.compare("9") == 0) {
            if(m_standardpara_temp.of != mStandardPara->of){
                m_standardpara_temp.of = mStandardPara->of;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"停止时间",mStandardPara->of);
            }
        }
        else if(sequence.compare("10") == 0) {
            if(m_standardpara_temp.currWeld1Vol != mStandardPara->currWeld1Vol) {
                m_standardpara_temp.currWeld1Vol = mStandardPara->currWeld1Vol;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"实际焊接1电压",mStandardPara->currWeld1Vol);
            }
        }
        else if(sequence.compare("11") == 0) {
            if(m_standardpara_temp.currWeld2Vol != mStandardPara->currWeld2Vol) {
                m_standardpara_temp.currWeld2Vol = mStandardPara->currWeld2Vol;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"实际焊接2电压",mStandardPara->currWeld2Vol);
            }
        }
        else if(sequence.compare("12") == 0) {
            if(m_standardpara_temp.preCurrVol != mStandardPara->preCurrVol) {
                m_standardpara_temp.preCurrVol = mStandardPara->preCurrVol;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接1电压",mStandardPara->preCurrVol);
            }
        }
        else if(sequence.compare("13") == 0) {
            if(m_standardpara_temp.weldCurrVol != mStandardPara->weldCurrVol) {
                m_standardpara_temp.weldCurrVol = mStandardPara->weldCurrVol;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接2电压",mStandardPara->weldCurrVol);
            }
        }
        else if(sequence.compare("14") == 0) {
            if(m_standardpara_temp.weldCount != mStandardPara->weldCount) {
                m_standardpara_temp.weldCount = mStandardPara->weldCount;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接次数",mStandardPara->weldCount);
            }
        }
        else if(sequence.compare("15") == 0) {
            if(m_standardpara_temp.weldPreCount != mStandardPara->weldPreCount) {
                m_standardpara_temp.weldPreCount = mStandardPara->weldPreCount;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"焊接预置数",mStandardPara->weldPreCount);
            }
        }
        else if(sequence.compare("16") == 0) {
            if(( m_standardpara_temp.scaleWeight != mStandardPara->scaleWeight ) ) {
                m_standardpara_temp.scaleWeight = mStandardPara->scaleWeight;
            }
        }
        else if(sequence.compare("17") == 0) {
            if(m_standardpara_temp.ultraSonicDistance != mStandardPara->ultraSonicDistance) {
                m_standardpara_temp.ultraSonicDistance != mStandardPara->ultraSonicDistance;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"超声波距离",mStandardPara->ultraSonicDistance);
            }
        }
        else if(sequence.compare("18") == 0) {
            if(m_standardpara_temp.temperarture != mStandardPara->temperarture) {
                m_standardpara_temp.temperarture = mStandardPara->temperarture;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"温度",mStandardPara->temperarture);
            }
        }
        else if(sequence.compare("19") == 0) {
            if(m_standardpara_temp.ammeterData != mStandardPara->ammeterData) {
                m_standardpara_temp.ammeterData = mStandardPara->ammeterData;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量",mStandardPara->ammeterData);
            }
        }
        else if(sequence.compare("20") == 0) {
            if(m_standardpara_temp.scaleCount != mStandardPara->scaleCount) {
                m_standardpara_temp.scaleCount = mStandardPara->scaleCount;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"实际数量",mStandardPara->scaleCount);

            }
        }
        else if(sequence.compare("21") == 0) {
            if(m_standardpara_temp.defectiveNumber != mStandardPara->defectiveNumber) {
                m_standardpara_temp.defectiveNumber = mStandardPara->defectiveNumber;
                m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"不良品数",mStandardPara->defectiveNumber);
            }
        }
        else if (sequence.compare("22") == 0) {
            m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"累计数量",mStandardPara->totalCount_FromScale);//TODO 20180730 add need test
        }
    }
}

void MashWelder::getWarnDisplay_switch(int warnValue)
{   
    if(m_warnValueinfo == warnValue) return;
    //ui->scrollTextWidget->killTimerId();
    m_warnValueinfo = warnValue;
    QString info = QString("%1").arg(m_warnValueinfo,9,2);//9 is the width
    if(info.length()==9) {
        if(info.at(0)=='1') {
            m_ScrollWarnSwitch.warnswitch1 = true;
        }
        if(info.at(1)=='1') {
            m_ScrollWarnSwitch.warnswitch2 = true;
        }
        if(info.at(2)=='1') {
            m_ScrollWarnSwitch.warnswitch3 = true;
        }
        if(info.at(3)=='1') {
            m_ScrollWarnSwitch.warnswitch4 = true;
        }
        if(info.at(4)=='1') {
            m_ScrollWarnSwitch.warnswitch5 = true;
        }
        if(info.at(5)=='1') {
            m_ScrollWarnSwitch.warnswitch6 = true;
        }
        if(info.at(6)=='1') {
            m_ScrollWarnSwitch.warnswitch7 = true;
        }
        if(info.at(7)=='1') {
            m_ScrollWarnSwitch.warnswitch8 = true;
        }
        if(info.at(8)=='1') {
            m_ScrollWarnSwitch.warnswitch9 = true;
        }
    }
    int swi = 0;
    swi |= (int)(((int)m_ScrollWarnSwitch.warnswitch1&0x01)<<0);
    swi |= (int)(((int)m_ScrollWarnSwitch.warnswitch2&0x01)<<1);
    swi |= (int)(((int)m_ScrollWarnSwitch.warnswitch3&0x01)<<2);
    swi |= (int)(((int)m_ScrollWarnSwitch.warnswitch4&0x01)<<3);
    swi |= (int)(((int)m_ScrollWarnSwitch.warnswitch5&0x01)<<4);
    swi |= (int)(((int)m_ScrollWarnSwitch.warnswitch6&0x01)<<5);
    swi |= (int)(((int)m_ScrollWarnSwitch.warnswitch7&0x01)<<6);
    swi |= (int)(((int)m_ScrollWarnSwitch.warnswitch8&0x01)<<7);
    swi |= (int)(((int)m_ScrollWarnSwitch.warnswitch9&0x01)<<8);

    m_systemStatus |= (swi << 3);
    //qDebug() << "~~~~~~KKKKKKKK~~~~~~~~~~~~~:"<<m_systemStatus;
    if(swi)
    {
        _isBroken = true;
        /*PLC Alarm*/
        //m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","04 00",false);

    }
    else
    {
        _isBroken = false;
        /*----zhanglong
        m_systemStatus &= 0x10;*/
    }

    //QStringList listRet;
    for(int i=0;i<m_warnList.count();i++) {
        if(swi&(0x01<<i)) {
            //listRet.append(m_warnList.at(i));
            insertDataToWarn(m_warnCodeList.at(i),m_warnContentList.at(i),QDateTime::currentDateTime());
        }
    }
}

void MashWelder::login()
{
    QWidget * back = new QWidget(this);
    back->setGeometry(WINDOW_GEOMETRY(1,1));
    back->setStyleSheet("background-color : rgba(0,0,0,200)");
    back->show();

    LoginDialog *lg = new LoginDialog(back);
    lg->show();
    connect(lg,SIGNAL(hasLogin()),back,SLOT(deleteLater()));
}

void MashWelder::insertDataToWarn(QString warn_code, QString warn_content, QDateTime add_time)
{
    DataBaseQuery query(DataBase::getDataBase());
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QMap<QString,QVariant> map_Save;
    map_Save.insert(DBTab_Warn::_TAB_WARN_CODE,QVariant(warn_code));
    map_Save.insert(DBTab_Warn::_TAB_WARN_CONTENT,QVariant(warn_content));
    map_Save.insert(DBTab_Warn::_ADD_TIME,QVariant(add_time));
    query.insert(DBTab_Warn::TAB_WARN,map_Save);
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();
}

void MashWelder::initScaleSerialSetting()
{
    QString portName = m_usbPortName.port1_name;   //获取串口名

#ifdef Q_OS_LINUX
    m_scaleCom = new QextSerialPort("/dev/" + portName);
#elif defined (Q_OS_WIN)
    if(m_scaleCom == NULL)
    {
        m_scaleCom = new QextSerialPort(portName);
    }
#endif
    connect(m_scaleCom, SIGNAL(readyRead()), this, SLOT(readScaleCom()));
    //设置波特率
    //m_scaleCom->setBaudRate((BaudRateType)9600);
    m_scaleCom->setBaudRate((BaudRateType)4800); //2018.11.20 Chenjiangang reduce baud rate from 9600 to 4800
    //设置数据流控制
    m_scaleCom->setFlowControl(FLOW_OFF);
    //设置延时
    m_scaleCom->setTimeout(50);
    if(!m_scaleCom->isOpen()) {
        m_scaleCom->open(QIODevice::ReadWrite);
    }
    //设置数据位
    m_scaleCom->setDataBits((DataBitsType)8);
    //设置校验
    m_scaleCom->setParity(PAR_NONE);
    m_scaleCom->setStopBits(STOP_1);
}

// CLOSE_2
void MashWelder::setWeldEnable_unChecked()
{
    if (ui->btn_weldEnable->isChecked()){
        ui->btn_weldEnable->setChecked(false);
    }
    //QMessageBox::warning(this, "01", "close_2", QMessageBox::Ok);
    m_modbusWnd->writeCmd("01","05","03","","RTU","","00 00",false);//close

    ui->btn_weldEnable->setText("焊接开");//only tips for next press;
}

void MashWelder::initModbusSetting()
{
    m_modbusWnd =  ModbusRtuMaster::getobj("/dev/" + m_usbPortName.port2_name,"115200","8","none","1");
    connect(m_modbusWnd,SIGNAL(sendStandardData_fromModbus(QString)),this,SLOT(receiveStandardData_fromModbus(QString)),Qt::QueuedConnection);
    connect(m_modbusWnd,SIGNAL(sendWarnData_fromModbus(int)),this,SLOT(receiveWarnData_fromModbus(int)),Qt::QueuedConnection);
    m_modbusWnd->readDataFromModbusSlave("01","03","00","0F","RTU","");//读焊接规范号参数
    m_modbusWnd->readDataFromModbusSlave("01","03","10","10","RTU","");//读系统信息参数
    m_modbusWnd->readDataFromModbusSlave("01","02","00","10","RTU","");//读警报信息参数
    m_modbusWnd->onChkAutoSendToggled(true);
}

void MashWelder::enableButton(bool bl)
{
    ui->btn_start->setEnabled(bl);
    ui->btn_preLoadValveOpen->setEnabled(bl);
    ui->btn_weldEnable->setEnabled(bl);
    ui->btn_weldCount_clear->setEnabled(bl);
    ui->btn_standardNum_set->setEnabled(bl);
    //ui->pushButton_4->setEnabled(bl);
    ui->btn_warnRecord_query->setEnabled(bl);
    ui->btn_sysInfo->setEnabled(bl);
    //ui->btn_login->setEnabled(bl);
    ui->btn_contact->setEnabled(bl);
    ui->btn_firstProduction->setEnabled(bl);
    ui->btn_QcFirstCheck->setEnabled(bl);
}

void MashWelder::initComboBox()
{
    ui->comboBox_warning->setCurrentIndex(-1);
    if(ui->comboBox_warning->currentIndex() == -1) {
        m_warningTimes = 0;
    }
}

void MashWelder::judgingVolAlarms()
{
    if(mStandardPara->currWeld1Vol.compare("0")==0)
        return;
    if( (m_weldingTimes_temp != mStandardPara->weldCount.toInt()) && ui->comboBox_warning->currentIndex() != -1)
    {
        m_weldingTimes_temp = mStandardPara->weldCount.toInt();
        if(mStandardPara->currWeld1Vol.toFloat() >= (mStandardPara->preCurrVol.toFloat() - m_DefVol) && \
                mStandardPara->currWeld1Vol.toFloat() <= (mStandardPara->preCurrVol.toFloat() + m_DefVol))
        {

        }
        else
        {
            m_warningTimes++;
            ui->lab_warnTimes->setText(QString::number(getWarningTimes()));
            if(getWarningTimes() == 1)
            {
                MyMessageDialog::message(this,"warning","Disable the welding Enable!");
                // 焊接使能发送复位
                m_modbusWnd->writeCmd("01","05","03","","RTU","","00 00",false);

                if(ui->btn_weldEnable->isChecked()) {
                    ui->btn_weldEnable->setChecked(false);
                }
                ui->btn_weldEnable->setEnabled(false);
                ui->btn_preLoadValveOpen->setEnabled(false);
#ifndef SHOW
                ui->btn_start->setEnabled(false);
#endif
            }
            else if(getWarningTimes() == 3) {
                fullScreenModalDlg *warningDialog = new fullScreenModalDlg(QString("焊接电压触发报警超过三次......\n请组长刷卡确认后，重置！"),this,false);
                m_deviceState->setDeviceStation(DeviceState::MAINTAIN_STATION);
                warningDialog->show();
                m_modbusWnd->writeCmd("01","05","03","","RTU","","00 00",false);
                /*vol alarm over three time----zhanglong*/
                m_systemStatus |= 0x0004;
                ui->btn_weldEnable->setEnabled(false);
                if(ui->btn_weldEnable->isChecked()) {
                    ui->btn_weldEnable->setChecked(false);
                }
                ui->btn_preLoadValveOpen->setEnabled(false);
#ifndef SHOW
                ui->btn_start->setEnabled(false);
#endif
                connect(this,                   SIGNAL(deleteWarnningDialog_signals()),    warningDialog,    SLOT(reject()));
            }
        }
    }
}

void MashWelder::deleleMashWarningDialog()
{
    emit deleteWarnningDialog_signals();
}

void MashWelder::removeDefectNumEvent()
{
    ui->le_defectiveNumber->removeEventFilter(this);
}


void MashWelder::setOrderButtonDisabled()
{
    ui->btn_orderCompleted->setEnabled(false);
}

void MashWelder::setOrderButtonShow()
{
    ui->btn_orderCompleted->show();
    ui->btn_weldEnable->setEnabled(true);
}

void MashWelder::setOrderButtonHidden()
{
    ui->btn_orderCompleted->hide();
}

void MashWelder::deleteSpotScrollText()
{
    if (m_spotDelayTimer) {
        if (m_spotDelayTimer->isActive()) {
            m_spotDelayTimer->stop();
        }
    }
    ui->spotCheckScroll->hide();
}

void MashWelder::startSpotCheckTimer()
{
    if (m_spotDelayTimer) {
        if (!m_spotDelayTimer->isActive()) {
            m_spotDelayTimer->start();
        }
    }
}

void MashWelder::termitTimer()
{
    if(m_heartBeatTimer) {
        if(m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->stop();
        }
    }
    m_modbusWnd->toggleAutoSendFun(false);
}

void MashWelder::receiveStandPapa_ofStandSet(int value)
{
    if(m_heartBeatTimer) {
        if(m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->stop();
        }
    }
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","00","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveSQ_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","01","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveSO_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","02","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveS1_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","03","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveW1_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","04","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveCO_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","05","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveW2_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","06","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveHO_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","07","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveOF_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","08","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receivePrecurr_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","09","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveWeldcurr_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","0A","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveWeldPreCounts_ofStandSet(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","0E","01","RTU","02",QString::number(value),true);

    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::preLoadValveOpen_slot()
{
    m_modbusWnd->toggleAutoSendFun(false);
    if(ui->btn_preLoadValveOpen->isChecked()) {
        m_modbusWnd->writeCmd("01","05","01","","RTU","","FF 00",false);
    }
    else {
        m_modbusWnd->writeCmd("01","05","01","","RTU","","00 00",false);

    }
    m_modbusWnd->toggleAutoSendFun(true);
}


//CLOSE_1
void MashWelder::weldEnable_Slot()
{
    if(ui->btn_weldEnable->isChecked()) {
        m_modbusWnd->writeCmd("01","05","03","","RTU","","FF 00",false);//open

        ui->btn_weldEnable->setText("焊接关"); //only tips for next press;
    }
    else {
        m_modbusWnd->writeCmd("01","05","03","","RTU","","00 00",false);//close
        //m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","02 00",false);
        ui->btn_weldEnable->setText("焊接开");//only tips for next press;
        //QMessageBox::warning(this, "01", "close_1", QMessageBox::Ok);
    }
}

void MashWelder::weldStart_PressCmd()
{       
    m_modbusWnd->toggleAutoSendFun(false);
    m_modbusWnd->writeCmd("01","05","00","","RTU","","FF 00",false);
    m_modbusWnd->toggleAutoSendFun(true);
}

void MashWelder::weldStart_ReleaseCmd()
{
    m_modbusWnd->toggleAutoSendFun(false);
    m_modbusWnd->writeCmd("01","05","00","","RTU","","00 00",false);
    m_modbusWnd->toggleAutoSendFun(true);
}

void MashWelder::weldCountClear_PressCmd() //清除焊接次数
{
    sender()->blockSignals(true);
    //TODO 20180805
    QString tips = tr("确定清除焊接次数？");
    MyMessageDialog *dialog = new MyMessageDialog(tips,tr("警告!"),this,tr("否"),tr("确定"));
    if(dialog->exec() == QDialog::Accepted)
    {
        saveElectrodeCountToDataBase(); //存储电极使用数量 //TODO 20180805
        /*clear wled count ----zhanglong ---test---20181127*/
        m_modbusWnd->writeCmd("01","05","04","","RTU","","FF 00",false); // clear welding count cmd
        m_modbusWnd->writeCmd("01","05","04","","RTU","","00 00",false); // release welding count
    }
    sender()->blockSignals(false);
}

void MashWelder::weldCountClear_ReleaseCmd()
{
    /*clear wled count ----zhanglong ---test---20181127*/
    m_modbusWnd->writeCmd("01","05","04","","RTU","","00 00",false); //close  ji shu

}

void MashWelder::weldWarnClearCmd()
{
    //TODO 发送报警清除命令---待测试 Doesn't work
    m_modbusWnd->writeCmd("01","05","07","","RTU","","FF 00",false); //warnning clear
}

void MashWelder::showStandardParaSetting()
{
    ui->stackedWidget->setCurrentWidget(ui->page_standardset);
    QLayout *layout = ui->frame_standard->layout();
    mStandardParaSetting = new StandardParaSetting(ui->frame_standard,layout,ui->frame_standard->width(),ui->frame_standard->height(),mStandardPara);
    connect(mStandardParaSetting,   SIGNAL(exitcurr()),                                     this,                   SLOT(receiveExitStand_Slot()));
    connect(mStandardParaSetting,   SIGNAL(StandardParaValue(int)),                         this,                   SLOT(receiveStandPapa_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardSQValue(int)),                           this,                   SLOT(receiveSQ_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardSOValue(int)),                           this,                   SLOT(receiveSO_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardS1Value(int)),                           this,                   SLOT(receiveS1_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardW1Value(int)),                           this,                   SLOT(receiveW1_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardCOValue(int)),                           this,                   SLOT(receiveCO_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardW2Value(int)),                           this,                   SLOT(receiveW2_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardHOValue(int)),                           this,                   SLOT(receiveHO_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardOFValue(int)),                           this,                   SLOT(receiveOF_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardPrecurrValue(int)),                      this,                   SLOT(receivePrecurr_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardWeldcurrValue(int)),                     this,                   SLOT(receiveWeldcurr_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(StandardWeldPreCounts(int)),                     this,                   SLOT(receiveWeldPreCounts_ofStandSet(int)));
    connect(mStandardParaSetting,   SIGNAL(termitTime_stanSet()),                           this,                   SLOT(termitTimer()));
    connect(this,                   SIGNAL(standardPara_refresh(StandardPara*)),            mStandardParaSetting,   SLOT(receiveStandard_refresh(StandardPara*)));
    connect(this,                   SIGNAL(closeInputDialog_ByHeadMan()),                   mStandardParaSetting,   SIGNAL(closeInputDialog_ByHeadMan()));
    connect(this,                   SIGNAL(closeSenconConfirmDialog_ByQcMan()),             mStandardParaSetting,   SIGNAL(closeSenconConfirmDialog_ByQcMan()));
    mStandardParaSetting->show();
}

void MashWelder::showContactUsSetting()
{
    ui->stackedWidget->setCurrentWidget(ui->page_contactus);
    QLayout *layout = ui->frame_contactus->layout();
    m_ContactUsSet = new ContactUsSet(layout,ui->frame_contactus->width(),ui->frame_contactus->height(),ui->frame_contactus);
    connect(m_ContactUsSet,SIGNAL(exitCurr()),this,SLOT(receiveExitContact_Slot()));
    m_ContactUsSet->show();
}

void MashWelder::showQueryWarnTable()
{
    ui->stackedWidget->setCurrentWidget(ui->page_warnRecord_query);
    QLayout *layout = ui->frame_warn_record->layout();
    m_WarnReord = new WarnRecordQuery(layout,ui->frame_warn_record->width(),ui->frame_warn_record->height(),ui->frame_warn_record);
    connect(m_WarnReord,SIGNAL(exitCurr()),this,SLOT(exitToMainUi()));
    m_WarnReord->show();
}

void MashWelder::showLogonRightsEditSetting()
{
    ui->stackedWidget->setCurrentWidget(ui->page_logon_rights);
    QLayout *layout = ui->frame_logon->layout();
    m_LogonRightsEdit = new LogonRightsEdit(layout,ui->frame_logon->width(),ui->frame_logon->height(),ui->frame_logon);
    connect(m_LogonRightsEdit,SIGNAL(exitCurr()),this,SLOT(exitToMainUi()));
    m_LogonRightsEdit->show();
}

void MashWelder::receiveExitStand_Slot()
{
    ui->stackedWidget->setCurrentWidget(ui->page_mashwelder);
}

void MashWelder::receiveExitContact_Slot()
{
    ui->stackedWidget->setCurrentWidget(ui->page_mashwelder);
}

void MashWelder::exitToMainUi()
{
    ui->stackedWidget->setCurrentWidget(ui->page_mashwelder);
}

void MashWelder::on_btn_sysInfo_clicked()
{
    ui->stackedWidget->setCurrentWidget(ui->page_weldinfo);
    QLayout *layout = ui->frame_weldinfo->layout();
    mWeldInfoSetting = new WeldInfoSetting(ui->frame_weldinfo,layout,ui->frame_weldinfo->width(),ui->frame_weldinfo->height());
    connect(mWeldInfoSetting,SIGNAL(exitcurr()),this,SLOT(receiveExitStand_Slot()));
    connect(this,SIGNAL(showScaleWeight(QString)),mWeldInfoSetting,SLOT(receiveScaleWeight(QString)));
    connect(this,SIGNAL(showScaleCount(QString)),mWeldInfoSetting,SLOT(receiveScaleCount(QString)));
    connect(this,SIGNAL(showDistance(QString)),mWeldInfoSetting,SLOT(receiveDistance(QString)));
    connect(this,SIGNAL(showTemperature(QString)),mWeldInfoSetting,SLOT(receiveTemperature(QString)));
    connect(this,SIGNAL(showAmmeterData(QString)),mWeldInfoSetting,SLOT(receiveAmmeterData(QString))); //
    connect(this,SIGNAL(showAmmeterVolData(QString)),mWeldInfoSetting,SLOT(receiveAmmeterVolData(QString)));
    connect(this,SIGNAL(showLaserDistanceAtSys(QString)),mWeldInfoSetting,SLOT(receiveLaserDistanceFromMain(QString)));
    mWeldInfoSetting->show();
}

void MashWelder::writeStandardPara() //向焊接规范号写值 提供参考
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","00","01","RTU","02",QString::number(ui->le_weld_standard_num->text().toInt()),true);
    if(m_heartBeatTimer) {
        if(!m_heartBeatTimer->isActive()) {
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::receiveHttpRegisterOK(bool registerOK)
{
    //qDebug()<<"+++++++++++++++++++++++++current_count:"<<registerOK;
    if(registerOK&& !m_pos_currentCount)
    {
        //qDebug()<<"+++++++++++++++++++++Yest";
        //        m_pos_currentCount = true;
        //        if(mStandardPara->scaleCount.isEmpty() == true)
        //            m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"CurrentCount","0");
        //        else
        m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"CurrentCount",ui->le_calibratedCount->text());
    }
}

/*Net break LED yello----zhanglong*/
void MashWelder::httpRegister_slots(bool status)
{
    if(status)
    {
        m_systemStatus &= 0xdfff;
    }
    else
    {
        m_systemStatus |= 0x2000;
        //qDebug() << "~~~~~~NNNNNNNN~~~~~~~~~~~~~:"<<m_systemStatus;
    }
    if(status && !m_register_flag) {
        m_register_flag = true;
        m_httpClient->registerDeviceInfo( m_deviceInfo->deviceType,m_deviceInfo->deviceId,"register",QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    }
}

void MashWelder::updateCurrentCountCirle()
{

    if(m_currentCount_temp.compare(ui->le_calibratedCount->text()) != 0){
        m_currentCount_temp = ui->le_calibratedCount->text();
        m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"CurrentCount",ui->le_calibratedCount->text());
    }
}


void MashWelder::receiveStation_fromHttp(QString station)
{
    m_currentStation = station;
}

void MashWelder::receiveModbusConnected(QString connectedStr)
{
    if(connectedStr.compare("Connected") == 0){

    }
}

void MashWelder::receiveModbusDisconnected(QString errString)
{
    if(!errString.isEmpty()) {
        m_receiveData = "";
        mStandardPara->co="";
        mStandardPara->currWeld1Vol="";
        mStandardPara->currWeld2Vol="";
        mStandardPara->ho="";
        mStandardPara->of="";
        mStandardPara->preCurrVol="";
        mStandardPara->s1="";
        mStandardPara->so="";
        mStandardPara->sq="";
        mStandardPara->w1="";
        mStandardPara->w2="";
        mStandardPara->weldCount="";
        mStandardPara->weldCurrVol="";
        mStandardPara->weldPreCount="";
        mStandardPara->weldStandardNum="";
    }
}

void MashWelder::postSerialNum_Slots()
{    
    ProductionVariant productinfo;
    QString order_flag;
    queryCurrentOrder(productinfo,order_flag);
    m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"TaskId",productinfo.TaskId);
}

void MashWelder::updateDeviceState_Slots()
{
    ProductionVariant productinfo;
    queryCurrentOrder(productinfo,m_currentTaskId);
    m_deviceState->setMachineState(DeviceState::MACHINE_WORKING);//string value is : processing
    QString deviceState;
    m_deviceState->getMachineStateString(deviceState);
    m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"State",deviceState);
    /*--- POST订单状态 ----*/
    m_httpClient->postOrderState(m_deviceState->getOrderState(),m_deviceInfo->deviceType,m_deviceInfo->deviceId,productinfo.TaskId);
}

//开始生产发送
void MashWelder::sendDatasAboutOrder()
{
    QString status;
    if(_isBroken)
        status = "故障";
    else if( ui->le_weldcount->text().toInt() != 0 )
        status = "生产中";
    else
        status = "待机中";
    m_httpClient->posOrderInfo( m_deviceInfo->deviceType, m_deviceInfo->deviceId, "status", status);
}

void MashWelder::slot_CloseWeldEnable()
{
    if( MainWidget::_FirstCheckPass && MainWidget::_QCCheckPass  )
    {
        _weldEnableTimer->stop();
        ui->btn_weldEnable->setDisabled(false);
        MainWidget::_FirstCheckPass = false;
        MainWidget::_QCCheckPass = false;
        weldEnable_Slot();
        return;
    }

    setWeldEnable_unChecked();
    ui->btn_weldEnable->setDisabled(true);
}

void MashWelder::on_le_weldcount_textChanged( QString str)
{
    if(!_orderBegin)
    {
        return;
    }
    //_isWorking = str.toInt() == 0 ? false : true;
    m_electrode_remainCount = ElectrodeSetWidget::getElectrode_remainCount();
    m_electrode_preCount = ElectrodeSetWidget::getElectrode_preCount();
    if (m_electrode_remainCount==0)
    {
        //do nothing, xuyifu 2018 11/17;
    }
    else
    {
        ElectrodeSetWidget::setElectrode_remainCount(m_electrode_remainCount-1);
        m_electrode_remainCount = ElectrodeSetWidget::getElectrode_remainCount();
        ElectrodeSetWidget::setElectrode_currentCount(m_electrode_preCount-m_electrode_remainCount);
    }

    if(str.toInt() <= 0)
    {
        return;
    }

    if( str.compare(ui->le_precount->text())==0 && ui->le_precount->text().toInt() > 0)
    {
        MyMessageDialog::message(0,"警告！"," 焊接次数达到预制数！",2000);
    }


    _iNum++; //每次进来计数+1
    if ( _iNum < TIME_SEND )
    {
        _writeNum_arr.append(get7datas_fromUI());
        return;
    }

    if(_iNum >= TIME_SEND)
    {
        _writeNum_arr.append(get7datas_fromUI()); //必须获取一下
        send7Datas();
        _iNum = 0;
        while(false ==_writeNum_arr.isEmpty() )
            _writeNum_arr.removeFirst();
    }
}


void MashWelder::sendUpdateTodayTask()
{
    QString status;
    if( ui->le_workNum->text().isEmpty() )
    {
        status = "待机";
    }
    else if(_isWorking)
    {
        status = "生产中";
    }
    else
    {
        status = "已完成";
    }

    QJsonObject obj;
    obj["productname"] = mParent->_productionVariant.ProductName;
    obj["productcode"] = mParent->_productionVariant.ProductCode;
    obj["taskstatus"] = status;
    if( ui->le_weldcount->text().toInt() != 0)
    {
        obj["taskyield"] = "0";
    }
    if(ui->le_calibratedCount->text().toInt() > 0)
        obj["finishedproduct"] = ui->le_calibratedCount->text();
    else
        obj["finishedproduct"] = "0";

    obj["device_property"] = QJsonObject();
    if( mStandardPara->ammeterData.contains("kWh"))
        mStandardPara->ammeterData.remove("kWh");

    if(mStandardPara->ammeterData.isEmpty())
        obj["energy"] = QString("0") ;
    else
        obj["energy"] = mStandardPara->ammeterData;

    obj["productcount"] = mParent->_productionVariant.WorkNum;
    obj["starttime"] = startTime;
    obj["TotalProductCount"]= ui->le_weldcount->text().toInt(); //weldcount 变TotalProductCount
    obj["offtime"] = endTime;
    m_httpClient->posTodayTask(m_deviceInfo->deviceType,
                               m_deviceInfo->deviceId,
                               mParent->_productionVariant.TaskId,
                               "task",
                               obj,
                               0);
}

void MashWelder::sendNotGood()
{
    m_httpClient->posNotGood(m_deviceInfo->deviceType,
                               m_deviceInfo->deviceId,
                               mParent->_productionVariant.TaskId,
                               "task",
                               m_defectiveNumber);
    //QMessageBox::warning(this, "123", QString::number(m_defectiveNumber), QMessageBox::Ok);
}

void MashWelder::sendOperatorAndMaterial()
{

    m_httpClient->posOperator( m_deviceInfo->deviceType,
                               m_deviceInfo->deviceId,
                               mParent->_productionVariant.TaskId,  _objToserver.value("Operator").toObject() , DeviceState::OPERATOR_WORK_STATION );

    for( int i =0; i < _jsArrToserver.size(); ++i)
    {
        m_httpClient->posMaterial( m_deviceInfo->deviceType,
                                   m_deviceInfo->deviceId,
                                   mParent->_productionVariant.TaskId,  _jsArrToserver.at(i).toObject() );
//        QMessageBox::warning(this, "123",
//        "mname: " +_jsArrToserver.at(i).toObject().value("mname").toString(), QMessageBox::Ok );
    }
    _objToserver = QJsonObject();
    while( _jsArrToserver.size() > 0)
    {
        _jsArrToserver.removeFirst();
    }
}


void MashWelder::send7Datas()
{
    m_httpClient->pos7Datas(m_deviceInfo->deviceType,
                            m_deviceInfo->deviceId,
                            mParent->_productionVariant.TaskId,
                            _writeNum_arr  );
}

QJsonObject MashWelder::get7datas_fromUI()
{
    QJsonObject obj;
    obj.insert("焊接规范号", ui->le_weld_standard_num->text().toInt());
    obj.insert("焊接预制数", ui->le_precount->text().toInt());
    obj.insert("预压时间", ui->le_sq->text().toInt());
    obj.insert("加压时间", ui->le_so->text().toInt());
    obj.insert("缓升时间", ui->le_s1->text().toInt());
    obj.insert("焊接1时间", ui->le_w1->text().toInt());
    obj.insert("冷却时间", ui->le_co->text().toInt());
    obj.insert("焊接2时间", ui->le_w2->text().toInt());
    obj.insert("维持时间", ui->le_ho->text().toInt());
    obj.insert("停止时间", ui->le_of->text().toInt());
    obj.insert("焊接1电压", ui->le_precurrvol->text().toInt());
    obj.insert("焊接2电压", ui->le_weldcurrvol->text().toInt());
    obj.insert("实际焊接1电压", ui->le_curr_weld1_vol->text().toInt());
    obj.insert("实际焊接2电压", ui->le_curr_weld2_vol->text().toInt());
    obj.insert("当前时间", QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz")  );
    obj.insert("电能",  mStandardPara->ammeterData );
    obj.insert("焊接次数",  ui->le_weldcount->text().toInt());

    return obj;
}


//订单完成时，发送
void MashWelder::slot_send7data()
{

}

void MashWelder::slot_clearOrderMsg()
{
    ui->le_productName->clear();
    ui->le_workNum->clear();
    ui->le_workTime->clear();
    ui->lbl_orderNum->clear();
    ui->le_calibratedCount->setText("0");
    sendNotGood();
}

void MashWelder::slot_sendOperator(QString strUserName, QString strUserId, DeviceState::DeviceStion  dd)
{
    QJsonObject obj;
    obj.insert("Operator", strUserName );
    obj.insert("OperatorId", strUserId );
    obj.insert("createtime", QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
    _objToserver.insert("Operator", obj);
    m_httpClient->posOperator( m_deviceInfo->deviceType,
                                   m_deviceInfo->deviceId,
                                   mParent->_productionVariant.TaskId,  obj , dd);
}

void MashWelder::postWarnData(QString alarm, QString createtime)
{
    QJsonObject obj;
    obj.insert("alarm", alarm );
    obj.insert("createTime", createtime );
    m_httpClient->postWarningInfo( m_deviceInfo->deviceType,
                                   m_deviceInfo->deviceId,
                                   mParent->_productionVariant.TaskId,
                                   obj );

}

void MashWelder::postWarnData(QString alarmContent, QString updateTime, QString alarmType)
{
    QJsonObject obj;
    obj.insert("AlarmType", alarmType );
    obj.insert("UpdateTime", updateTime );
    obj.insert("AlarmContent",  alarmContent);
    m_httpClient->postWarningInfo( m_deviceInfo->deviceType,
                                   m_deviceInfo->deviceId,
                                   mParent->_productionVariant.TaskId,
                                   obj ,
                                   true);
}

void MashWelder::slot_sendMaterial(QString strCount, QString strMname, QString strMcode)
{
    QJsonObject obj;
    obj.insert("count", strCount );
    obj.insert("mname", strMname );
    obj.insert("mcode", strMcode );
    _jsArrToserver.append(obj);
}

void MashWelder::slot_sendGongZhang(QString strToolName,  QString strToolCode)
{
    QJsonObject obj;
    obj.insert("ToolingCode", strToolCode );
    obj.insert("ToolingName", strToolName );
    m_httpClient->posGongzhuang(m_deviceInfo->deviceType,
                                m_deviceInfo->deviceId,
                                mParent->_productionVariant.TaskId,
                                obj );
}


void MashWelder::startFirstProduction_slots()
{
    //ui-> btn_spotCheck->setEnabled(true);
    _orderBegin = true;
    _isWorking = true;
    m_orderFinish_flag = false;
    ui->btn_firstProduction->setEnabled(true);
    ui->btn_QcFirstCheck->setEnabled(true);
    startTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    endTime = QString("");
    sendUpdateTodayTask();
    _timerSendToserver->start(3000);
    m_systemStatus &= 0x7fff;
    _weldEnableTimer->start(3600 * 1000);
    exitToMainUi();
    setCurrentStandardPara_ByOrder(tProductionInfo);
    enableButton(true);
    ui->btn_firstProduction->show();
    ui->btn_QcFirstCheck->show();
    ui->btn_orderCompleted->show();
    m_qc_checkTimer->start(1000*60*60); //One hour

    /*zhanglong--20181219*/
    m_qc_checkDelayTimer->start(60000*120);

    connect(m_qc_checkTimer, SIGNAL(timeout()),this,SLOT(qcCheckFun()));
}

void MashWelder::currentUserShow(QString user)
{
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");//Last is GBK 20180428
    QString s;
    s = codec->toUnicode(user.toUtf8());
}

void MashWelder::resetWarning()
{
    m_warningTimes = 0;
    ui->lab_warnTimes->setText("");
    ui->btn_weldEnable->setEnabled(true);
    ui->btn_preLoadValveOpen->setEnabled(true);
    ui->btn_start->setEnabled(true);

    m_deviceState->setDeviceStation(DeviceState::OPERATOR_WORK_STATION);
}

void MashWelder::getCurrentTestVol(QString percent)
{
    float tempPercent = percent.remove("%").toFloat() / 100;
    float vol = mStandardPara->preCurrVol.toFloat() *tempPercent;
    m_DefVol = vol;
}

void MashWelder::receiveStandardData_fromModbus(QString standardData)
{
    m_receiveData = standardData;
}

void MashWelder::receiveWarnData_fromModbus(int warnData)
{
    getWarnDisplay_switch(warnData);
}

void MashWelder::deviceCircleTimeSlot()
{
    if (!m_postDeviceDetail_flag) {
        posDetailFun("");
        m_postDeviceDetail_flag = true;
        if(m_heartBeatTimer) {
            if (m_heartBeatTimer->isActive()) {
                m_heartBeatTimer->stop();
            }
        }
    }
}

QString MashWelder::getLocalHostIP()
{
    QList<QHostAddress> AddressList = QNetworkInterface::allAddresses();
    QHostAddress result;
    foreach (QHostAddress address, AddressList) {
        if(address.protocol() == QAbstractSocket::IPv4Protocol &&
                address != QHostAddress::Null &&
                address != QHostAddress::LocalHost) {
            if (address.toString().contains("127.0.")) {
                continue;
            }
            result = address;
            break;
        }
    }
    return result.toString();
}

QString MashWelder::macAddress()
{
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";
    for (int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && \
                nets[i].flags().testFlag(QNetworkInterface::IsRunning) && \
                !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack)) {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    return strMacAddr;
}

void MashWelder::setCurrentOrderStatusShow(ProductionVariant &productInfo)
{
    //qDebug() << Q_FUNC_INFO << "productInfo.ProductName: " << productInfo.ProductName;
    //qDebug() << Q_FUNC_INFO << "productInfo.WorkNum: " << productInfo.WorkNum;
    //qDebug() << Q_FUNC_INFO << "productInfo.WorkTime: " << productInfo.OrderStartTime;
    ui->le_productName->setText(productInfo.ProductName);
    ui->le_workNum->setText(productInfo.WorkNum);
    ui->le_workTime->setText(productInfo.OrderStartTime);
    ui->lbl_orderNum->setText(productInfo.TaskId);
    m_current_taskId = productInfo.TaskId;//TODO 20180730 add
}

void MashWelder::inputGoodNum()
{
    ui->le_calibratedCount->clearFocus();
    QWidget *back = new QWidget(this);
    back->setGeometry(0,0,SCREEN_WIDTH,SCREEN_HIGH);
    back->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); //Windows上设为透明色 需有Qt::FramelessWindowHint
    back->setAttribute(Qt::WA_TranslucentBackground,true); //Windows上设为透明色
    back->setWindowModality(Qt::WindowModal);
    back->show();
    inputDialog *inputdialog = new inputDialog(back,"请输入合格品",false,5,0,0,true);
    inputdialog->setWindowModality(Qt::WindowModal);
    inputdialog->hideSome();
    inputdialog->show();
    connect(inputdialog,SIGNAL(inputValue(int)),this,SLOT(accpetGoodValue(int)));
    connect(inputdialog,SIGNAL(exitInputdialog()),back,SLOT(deleteLater()));
    connect(inputdialog,SIGNAL(exitInputdialog()),inputdialog,SLOT(deleteLater()));
}

void MashWelder::accpetGoodValue(int val)
{
    ui->le_calibratedCount->setText(QString::number(val));
}

void MashWelder::readScaleCom()
{
    //2018.11.20 Chen Jiangang Reduce the frequency of Scale calculation for resource usage
    readScaleComDelay_count++;
    //qDebug() << "\n\n ~~~~~ readScaleComDelay_count:" << readScaleComDelay_count;

    if ( readScaleComDelay_count >= 5)
    {

        if (m_scaleCom->canReadLine() ) {
            QString temp = m_scaleCom->readAll();
            //qDebug() << "\n\n ~~~~~ temp scale readAll:" << temp;
            // ~~~~~ temp scale readAll: "\r\rST,GS   0.038kg\r    6.45546 g\n"
            // ~~~~~ temp scale readAll: "      6pcs\n"
            //~~~~~ temp scale readAll: "46 g\n      0pcs\n\r\rST,GS   0.000kg\r    6.45546 g\n      0pcs\n\r"
            //~~~~~ temp scale readAll: "\rST,GS   0.000kg\r    6.45546 g\n      0pcs\n\r\rST,GS   0.000kg\r"
            //~~~~~ temp scale readAll: "\rST,NT   0.000kg\r          0 g\n      0pcs\n\r\rST,NT   0.000kg\r          "
            //20181019 fix bug of GOOD patrs at UI sometimes show "10 S" or "10 ST"
            //if (temp.contains("pcs") && temp.length()<15)//T-Scale show pcs
            if (temp.contains("pcs") &&temp.contains("g\n") &&(temp.indexOf("g\n")<temp.indexOf("pcs")))//T-Scale show pcs  "1234567pcs\n"
            {
                //qDebug() << "\n\n pcs:" << temp;
                QString pcs="pcs";
                // QString count = temp.right(11).remove("pcs");

                //if (temp.mid(7,4)=="pcs\n")
                int indexOfpcs=0;
                indexOfpcs=temp.indexOf(pcs); //return the index position of first occurence of "pcs\n"
                //qDebug() << "\n\n return the index position of first occurence of pcs\n:" << indexOfpcs;
                if (indexOfpcs>=7) //make sure the pcs including 7 number:1234567pcs
                {
                    //QString count = temp.right(11).remove("pcs\n");
                    //~~~~~ temp scale readAll: "      7pcs\n"
                    //~~~~~ temp scale readAll: "1234567pcs\n"  //2018.8.10.  2g accuracy Tscale
                    //~~~~~ temp scale readAll: "    247pcs\r\n"//2018.11.17  1g accuracy Tscale
                    QString count;
                    // 2018/10/30 Chenjiangang @SVRU Tianjing
                    //get rid of Empty string due to noise when scale is wired with RS232 cable longer than 10m
                    if(!temp.mid(indexOfpcs-7,7).isEmpty())
                    {
                        count =temp.mid(indexOfpcs-7,7);


                        mStandardPara->scaleCount = count;
                        //qDebug() << "\n\n ~~~~~ mStandardPara->scaleCount" << mStandardPara->scaleCount;
                        emit showScaleCount(mStandardPara->scaleCount);
                        //"     10pcs\n"
                        //"1234567pcs\n"

                        if(m_postDeviceDetail_flag)
                        {
                            putDetailFun("20");
                        }
                    }
                }
            }

            //Chenjiangang,20181019,T-Scale is used in G-IOT project installed with 26sets
            //Chenjiangang,20181122, add "ST,NT" at Tare condition besides of "ST,GS" at normal condition
            if (temp.contains("ST,")&&temp.contains("kg\r")&&(temp.indexOf("ST,")<temp.indexOf("kg\r")))
            {
                //qDebug() << "\n\n string includig  ST,GS/ST,NT and kg\r:" << temp;
                QString ST="ST,";
                int indexOfST=0;
                indexOfST=temp.indexOf(ST); //return the index position of first occurence of "pcs\n"
                //qDebug() << "\n\n return the index position of first occurence of  ST," << indexOfST;
                if (indexOfST>=0) //make sure the total weight including "ST,GS"
                {
                    // if (temp.startsWith("\r\r")) {
                    //if(temp.mid(0,7)=="\r\rST,GS"){
                    //qDebug() << "\n\n ~~~~~ temp whole string before remove:" << temp;
                    //~~~~~ temp whole string before remove: "\r\rST,GS   0.038kg\r    6.45546 g\n"
                    //temp = temp.remove(0,1);
                    //~~~~~ temp whole string after remove: "\rST,GS   0.038kg\r    6.45546 g\n"  //2018.8.10.  2g accuracy Tscale
                    //              ~~~~~ temp scale readAll: "ST,GS   0.742kg\r          3 g\r\n" //2018.11.17  1g accuracy Tscale
                    //"\rST,GS    0.70kg\r    35.1217 g\n
                    QString scaleWeight;
                    // ~~~~~scaleWeight "   0.014"
                    // ~~~~~scaleWeight "0000.014"
                    // ~~~~~scaleWeight "  0.064k"
                    // ~~~~~scaleWeight "0pcs\n\r\rS"
                    // ~~~~~ temp scale readAll: "s\n\r\rST,GS   0.064kg\r"
                    // ~~~~~scaleWeight ",GS   0."
                    //"\r\rST,GS    0.466kg\r    46.1190 g\n"
                    //"\rST,GS   0.100kg\
                    //"\rST,GS12345678kg\


                    // 2018/10/30 Chenjiangang @SVRU Tianjing
                    //get rid of Empty string due to noise when scale is wired with RS232 cable longer than 10m
                    if(!temp.mid(indexOfST+5,8).isEmpty())
                    {
                        scaleWeight =temp.mid(indexOfST+5,8);
                        mStandardPara->scaleWeight = scaleWeight;
                        //qDebug() << "\n\n ~~~~~mStandardPara->scaleWeight" << mStandardPara->scaleWeight;
                        emit showScaleWeight(mStandardPara->scaleWeight);
                        if(m_postDeviceDetail_flag) {
                            putDetailFun("16");
                        }
                    }
                }

            }
            //chenjiangang,20181024, compare auto calibraiton count with Tscale counts and compensate cali-unitweight
            if (temp.contains("kg\r") &&temp.contains("g\n") &&(temp.indexOf("kg\r")<temp.indexOf("g\n"))) //get unitWeight before g\n
            {
                //qDebug() << "\n\n string includig kg_r and g\n:" << temp;
                QString kg_r="kg\r";
                int indexOfkg_r=0;
                indexOfkg_r=temp.indexOf(kg_r); //return the index position of first occurence of "pcs\n"
                //qDebug() << "\n\n return the index position of first occurence of  kg_r" << indexOfkg_r;
                if (indexOfkg_r>=0) //make sure the total weight including "kg_r"
                {

                    //qDebug() << "\n\n ~~~~~ temp whole string before remove:" << temp;
                    //~~~~~ temp whole string after remove: "\rST,GS   0.038kg\r    5.789AB g\n"
                    //~~~~~ temp whole string after remove: "\rST,GS   0.038kg\r12345.789AB g\n"
                    //"\rST,GS    0.70kg\r    35.1217 g\n
                    //~~~~~ temp whole string after remove: "\rST,GS   0.038kg\r    6.45546 g\n"   //2018.8.10.  2g accuracy Tscale
                    //              ~~~~~ temp scale readAll: "ST,GS   0.742kg\r          3 g\r\n" //2018.11.17  1g accuracy Tscale

                    QString scale_unitWeight;
                    //~~~~~ temp whole string after remove: "\rST,GS   0.038kg\r12345.789AB g\n"
                    //"\r\rST,GS    0.466kg\r    46.1190 g\n"

                    // 2018/10/30 Chenjiangang @SVRU Tianjing
                    //get rid of Empty string due to noise when scale is wired with RS232 cable longer than 10m
                    if(!temp.mid(indexOfkg_r+3,11).isEmpty())
                    {
                        scale_unitWeight =temp.mid(indexOfkg_r+3,11);
                        mStandardPara->scale_unitWeight = scale_unitWeight;
                        //qDebug() << "\n\n ~~~~~mStandardPara->scale_unitWeight" << mStandardPara->scale_unitWeight;
                        emit showscale_unitWeight(mStandardPara->scale_unitWeight);
                    }
                }

            }
            //TODO 20180806 Need confirm this
            //20181016 Chenjiangang update parts counting auto calibraiton method
            float currentWeight = mStandardPara->scaleWeight.toFloat()*1000;
            float currentUnitWeight = mStandardPara->scale_unitWeight.toFloat() ;

            m_scaleAmendInstance->getScaleSourceValue(currentWeight, currentUnitWeight);
            connect(this,SIGNAL(sendUw(float)),m_scaleAmendInstance,SLOT(getScaleUw(float)));
            connect(m_scaleAmendInstance,SIGNAL(sendCalibrationCount(int,float)),this,SLOT(getCalibrationCount(int,float)));
        }


        readScaleComDelay_count=0;
    }


#ifdef LINGHENG
    if(m_scaleCom->canReadLine()) {
        QString temp =  QString(m_scaleCom->readLine());
        mStandardPara->scaleWeight = QString::number( temp.mid(4,6).toFloat()/10);
        mStandardPara->scale_unitWeight = QString::number( temp.mid(16,6).toFloat()/10);
        mStandardPara->scaleCount = QString::number(temp.mid(22,6).toInt());
        emit showScaleWeight(mStandardPara->scaleWeight);
        emit showScaleCount(mStandardPara->scaleCount);
        if(m_postDeviceDetail_flag) {
            putDetailFun("16");
            putDetailFun("20");
        }

        //TODO 20180806 Need confirm this
        float currentWeight = mStandardPara->scaleWeight.toFloat();
        float currentUnitWeight = mStandardPara->scale_unitWeight.toFloat();
        m_scaleAmendInstance->getScaleSourceValue(currentWeight, currentUnitWeight);
        connect(this,SIGNAL(sendUw(float)),m_scaleAmendInstance,SLOT(getScaleUw(float)));
        connect(m_scaleAmendInstance,SIGNAL(sendCalibrationCount(int,float)),this,SLOT(getCalibrationCount(int,float)));
    }
#endif

}

void MashWelder::readUltraDistance(float distance)
{
    mStandardPara->ultraSonicDistance = QString::number(distance) + " cm";
    emit showDistance(mStandardPara->ultraSonicDistance);
    if(m_postDeviceDetail_flag) {
        putDetailFun("17");
    }
}

void MashWelder::readTemperature(float temperature)
{
    /*----zhanglong*/
    if(temperature > 40)
    {
        Alarm_Count ++;
        if(Alarm_Count > 2)
        {
            Alarm_Count = 3;
            m_systemStatus |= 0x0001;
        }
    }
    else
    {
        if(Alarm_Count != 0)
        {
            Alarm_Count --;
        }
        else
        {
            m_systemStatus &= 0xfffe;
        }
    }
    mStandardPara->temperarture = QString::number(temperature) + " °c";
    emit showTemperature(mStandardPara->temperarture);
    if(m_postDeviceDetail_flag) {
        putDetailFun("18");
    }
}

void MashWelder::acceptInputValue(int value)
{
    m_modbusWnd->toggleAutoSendFun(true);
    m_modbusWnd->writeCmd("01","10","00","01","RTU","02",QString::number(value),true);
    if(m_heartBeatTimer)
    {
        if(!m_heartBeatTimer->isActive()){
            m_heartBeatTimer->start();
        }
    }
}

void MashWelder::acceptInputValue_test(float value)
{
    ui->le_filterScale->setText(QString::number(value));
    m_scaleAmendInstance->setFilterScale(value);
    SettingReader::setFilterCoef(value);
}

void MashWelder::acceptDefectiveValue(int defectiveNum)
{
    if( defectiveNum >  ui->le_workNum->text().toInt())
    {
        MyMessageDialog::message(0,"警告！"," 不良品数量大于订单数！",2000);
        return;
    }

    m_defectiveNumber = defectiveNum;
    /* K1 = m_defectiveNumber;
     * K2 = M -N;
     * M = mStandardPara->weldCount;
     * N = totalCount_FromScale;
     * |K1 - K2| >5 --->show tips
     */

    int K1 = m_defectiveNumber;
    int M = mStandardPara->weldCount.toInt();
    int N= mStandardPara->totalCount_FromScale.toInt();
    int K2 = qAbs(M -N);

    if(  qAbs( ui->le_weldcount->text().toInt()-ui->le_calibratedCount->text().toInt() - _inputVal.toInt()) > 5 || _inputVal.toInt()< getWarningTimes() )
    {
        showDefectiveNumTips();
    }else{
        defectiveNumTipsCheckOK();
    }

    ui->le_defectiveNumber->setText(QString::number(m_defectiveNumber));
    mStandardPara->defectiveNumber = QString::number(m_defectiveNumber);
    //m_modbusWnd->writeCmd("01","05","04","","RTU","","FF 00",false);//计数清零
    //m_modbusWnd->writeCmd("01","05","04","","RTU","","00 00",false);//计数清零
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("21");
    }
}

void MashWelder::readAmmeterPowerData(float ammeter)
{
    mStandardPara->ammeterData = QString::number(ammeter) + " kWh";
    emit showAmmeterData(mStandardPara->ammeterData);
    if(m_postDeviceDetail_flag)
    {
        putDetailFun("19");
    }
}

void MashWelder::readAmmeterVolData(float vol)
{
    mStandardPara->ammeterVolData = QString::number(vol) + " V";
    emit showAmmeterVolData(mStandardPara->ammeterVolData);
}

void MashWelder::updateCurrentCount()
{
    m_updateCurrentCountTimer->start(1000);
    connect(m_updateCurrentCountTimer,   SIGNAL(timeout()),    this,   SLOT(updateCurrentCountCirle()));
}

void MashWelder::on_settingBtn_clicked()
{
    emit openSettingSignal();
}

void MashWelder::spotCheckManualExecute()
{
    ui->btn_spotCheck->setDisabled(true);
    m_systemStatus |= 0x4000;

    Equipment_ckeck = true;
    initSpotCheckEquipmentDialog();
}

void MashWelder::QCCheckManualExecute()
{
    ui->qc_scan_check->setDisabled(true);
    m_systemStatus |= 0x4000;
    QC_Scan_ckeck = true;
    initQCCheckDialog();
}

void MashWelder::QCCheckTimerTips()
{
    if(!_orderBegin)
    {
        return;
    }
    QC_Scan_ckeck = true;
    m_systemStatus |= 0x4000;
    ui->qc_scan_check->setEnabled(true);
}

void MashWelder::spotCheckTimerTips()
{
    /*QStringList list;*/
    /*ADD LED and Relax control*/
    m_systemStatus |= 0x4000;
    Equipment_ckeck = true;
    ui->btn_spotCheck->setEnabled(true);
    /*list << tr("请设备人员巡检设备！");
    ui->spotCheckScroll->show();
    ui->spotCheckScroll->startTimerId();
    ui->spotCheckScroll->setScrollText(list);*/
}

void MashWelder::recordScaleData_slots()
{    
    //if (mStandardPara->scaleWeight.toInt() <=0 )
    //2018.11.15 Chen Jiangang, optimize scale weight restore to DataBase for future use
    if ( mStandardPara->scaleWeight.toFloat()*1000 <=0)
    {
        MyMessageDialog::message(this,"警告","请检查电子秤是否设置关闭零点跟踪！");
    }
    DataBaseQuery query(DataBase::getDataBase());
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QMap<QString,QVariant> map_Save;
    map_Save.insert(DBTab_MashWelder::_TAB_MASHWELDER_SCALE_WEIGHT,QVariant(mStandardPara->scaleWeight.toFloat()));
    map_Save.insert(DBTab_MashWelder::_TAB_MASHWELDER_SCALE_COUNT,QVariant(/*ui->le_testCount->text().toInt()*/ ui->le_calibratedCount->text().toInt()));
    map_Save.insert(DBTab_MashWelder::_TAB_MASHWELDER_TASK_ID,QVariant(m_current_taskId));
    map_Save.insert(DBTab_MashWelder::_ADD_TIME,QVariant(QDateTime::currentDateTime()));
    query.insert(DBTab_MashWelder::TAB_MASHWELDER,map_Save);
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();
    DataBase::getDataBase().open();
    DataBase::getDataBase().transaction();
    QString str;
    str = "SELECT "
          " SUM(" + DBTab_MashWelder::TAB_MASHWELDER + "." + DBTab_MashWelder::_TAB_MASHWELDER_SCALE_WEIGHT + "),"\
                                                                                                              " SUM(" + DBTab_MashWelder::TAB_MASHWELDER + "." + DBTab_MashWelder::_TAB_MASHWELDER_SCALE_COUNT + ")"\
                                                                                                                                                                                                                 " FROM "  + DBTab_MashWelder::TAB_MASHWELDER +\
            " WHERE " + DBTab_MashWelder::TAB_MASHWELDER + "." + DBTab_MashWelder::_TAB_MASHWELDER_TASK_ID + " = " + "\""+ m_current_taskId + "\"";

    query.execQString(str);
    if (query.next()) {
        m_current_order_finished_weight = query.value(0).toFloat();
        m_current_order_finished_count = query.value(1).toInt();
        mStandardPara->totalCount_FromScale = QString::number(m_current_order_finished_count);
    }
    ui->le_calibratedCount->setText(mStandardPara->calibrationCount);
    putDetailFun("22");//Put the scale total Count;
    DataBase::getDataBase().commit();
    DataBase::getDataBase().close();
    MyMessageDialog::message(0,"提示！","当前称重存储本地数据库成功！",1500);

}

void MashWelder::getCalibrationCount(int calibrationCount,float unitweight)
{
    char fmt[]="%.2f";
    QString uw_str;
    uw_str.sprintf(fmt,unitweight);
    mStandardPara->calibrationCount = QString::number(calibrationCount);
    ui->le_calibratedCount->setText(QString::number(calibrationCount));
    ui->le_uw->setText(uw_str);
}

void MashWelder::on_pushButton_clicked()
{
    m_scaleAmendInstance->setReRunFlag(false);
    MyMessageDialog::message(0,"Tips!","Re-Calibration OK;",1500);

}

void MashWelder::LEDFrashCircleTimeSlot()
{
    /*status show*/
    /*Add Alarm text----zhanglong*/
    QStringList list;

    if(l_Equipment_ckeck != Equipment_ckeck)
    {
        if(Equipment_ckeck)
        {
            list << tr("请设备维护人员对设备进行点检！");
            ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);
        }
        else
        {
            list.clear();
        }
        l_Equipment_ckeck = Equipment_ckeck;
    }

    if (l_QC_Scan_ckeck != QC_Scan_ckeck)
    {
        if(QC_Scan_ckeck)
        {
            list << tr("请QC人员进行巡检！");
            ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);
        }
        else
        {
            if (!l_Equipment_ckeck){
                list.clear();
            }
        }
        l_QC_Scan_ckeck = QC_Scan_ckeck;
    }
    if(l_systemStatus != m_systemStatus)
    {
        /*LED Fresh*/
        if(m_systemStatus & 0x0fff)
        {
            //qDebug() << "+++++++++++++++ZZZZZZZZ:" <<m_systemStatus;
            m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","04 00",false);
        }
        else
        {
            if(m_systemStatus & 0xf000)
            {
                //qDebug() << "-------------ZZZZZZZZ:" <<m_systemStatus;
                m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","02 00",false);
            }
            else
            {
                if(_isWorking)
                {
                    m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","09 00",false);
                }
                else
                {
                    m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","01 00",false);
                }
            }
        }
        /*add CMD seng again-----zhanglong--20181219*/
        if(m_systemStatus & 0x0fff)
        {
            //qDebug() << "+++++++++++++++ZZZZZZZZ:" <<m_systemStatus;
            m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","04 00",false);
        }
        else
        {
            if(m_systemStatus & 0xf000)
            {
                //qDebug() << "-------------ZZZZZZZZ:" <<m_systemStatus;
                m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","02 00",false);
            }
            else
            {
                if(_isWorking)
                {
                    m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","09 00",false);
                }
                else
                {
                    m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","01 00",false);
                }
            }
        }

        l_systemStatus = m_systemStatus;

        if(Equipment_ckeck)
        {
            list << tr("请设备维护人员对设备进行点检！");
            /*ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);*/
        }
        else
        {
            list.clear();
        }
        if(QC_Scan_ckeck)
        {
            list << tr("请QC人员进行巡检！");
            /*ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);*/
        }
        else
        {
            if (!l_Equipment_ckeck){
                list.clear();
            }
        }

        if(m_systemStatus)
        {
            if(m_systemStatus & 0x0001)
            {
                list.append(AlarmList.at(0));
            }
            if(m_systemStatus & 0x0004)
            {
                list.append(AlarmList.at(2));
            }
            if(m_systemStatus & 0x0008)
            {
                list.append(AlarmList.at(3));
            }
            if(m_systemStatus & 0x0010)
            {
                list.append(AlarmList.at(4));
            }
            if(m_systemStatus & 0x0020)
            {
                list.append(AlarmList.at(5));
            }
            if(m_systemStatus & 0x0040)
            {
                list.append(AlarmList.at(6));
            }
            if(m_systemStatus & 0x0080)
            {
                list.append(AlarmList.at(7));
            }
            if(m_systemStatus & 0x0100)
            {
                list.append(AlarmList.at(8));
            }
            if(m_systemStatus & 0x0200)
            {
                list.append(AlarmList.at(9));
            }
            if(m_systemStatus & 0x0400)
            {
                list.append(AlarmList.at(10));
            }
            if(m_systemStatus & 0x0800)
            {
                list.append(AlarmList.at(11));
            }
            if(m_systemStatus & 0x2000)
            {
                list.append(AlarmList.at(13));
            }
            if(m_systemStatus & 0x4000)
            {
                list.append(AlarmList.at(14));
            }
            if(m_systemStatus & 0x8000)
            {
                list.append(AlarmList.at(15));
            }
            ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);
        }
        else
        {
            /*list.removeAll();*/
            if((!Equipment_ckeck) && (!QC_Scan_ckeck))
            {
                list.clear();
                ui->spotCheckScroll->hide();
            }
        }
        //list.append(AlarmList.at(2));
        //list = AlarmList.at(0)+AlarmList.at(2)+AlarmList.at(3)+AlarmList.at(4);

        if (!list.isEmpty())
        {
            for (int i=0;i<list.size();i++)
            {
                QString str = list.at(i);
                if (str.trimmed()!="")
                {
                    QString strTaskType;
                    if( getCurrentTaskId().isEmpty() )
                        strTaskType = "Device";
                    else
                        strTaskType = "TaskId";
                    postWarnData(str,QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"), strTaskType);
                    //postWarnData(str,QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
                }
            }
        }

    }
}

void MashWelder::on_btn_elecEnable_clicked()
{
    /*relax close manual*/
    m_ammeterDate->writeCmd("02","05","03","10","RTU","02","FF 00",false);
}
